# Getting started with KSP In this guide, you will learn: * How to add KSP-based annotation processors to your project. * How to create your own annotation processor with the KSP API. * Where to find the code generated by the processor. ## Add a KSP-based processor to your project To use an external processor in your project, add KSP to the [plugins {} block](https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block) in your `build.gradle(.kts)` file. If the processor is only needed in a specific module, add it to that module's `build.gradle(.kts)` file instead: Kotlin: ```KOTLIN // build.gradle.kts plugins { kotlin("jvm") version "2.4.21" id("com.google.devtools.ksp") version "2.3.12" } ``` Groovy: ```GROOVY // build.gradle plugins { id 'org.jetbrains.kotlin.jvm' version '2.4.21' id 'com.google.devtools.ksp' version '2.3.12' } ``` Tip: To find the latest version of KSP, check the GitHub [Releases](https://github.com/google/ksp/releases). In the top-level `dependencies {}` block, add the processor you want to use. This example uses [Moshi](https://github.com/square/moshi?tab=readme-ov-file#codegen), but the approach is the same for other processors: Kotlin: ```KOTLIN // build.gradle.kts dependencies { ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.2") } ``` Groovy: ```GROOVY // build.gradle dependencies { ksp 'com.squareup.moshi:moshi-kotlin-codegen:1.15.2' } ``` The `ksp(...)` configuration applies the processor only to application sources. To process test sources, add the processor with the `kspTest(...)` configuration. Note: The `ksp(...)` configuration is available only in single-platform projects. To learn how to configure processors for individual Kotlin Multiplatform targets and compilations, see [KSP with Kotlin Multiplatform](ksp-multiplatform.html). ## Create your own processor The following sections explain how to create a simple symbol processor that generates a `helloWorld()` function. While not very useful in practice, it demonstrates the basics of creating your own processors and annotations. ### Add KSP to the project Create a new Kotlin project and add the KSP plugin: 1. In IntelliJ IDEA, select File | New | Project. 2. In the list on the left, select Kotlin. 3. Select Gradle as the build system and click Create. ![Creating a new project](images/ksp-new-project.png) 4. Add the KSP plugin to the `build.gradle(.kts)` file: Kotlin: ```KOTLIN // build.gradle.kts plugins { kotlin("jvm") version "2.4.21" id("com.google.devtools.ksp") version "2.3.12" apply false } ``` Groovy: ```GROOVY // build.gradle plugins { id 'org.jetbrains.kotlin.jvm' version '2.4.21' id 'com.google.devtools.ksp' version '2.3.12' apply false } ``` ### Create an annotation Create a new module at the root of the project and declare an annotation: 1. Select File | New | Module. 2. In the list on the left, select Kotlin. 3. Specify the following fields and click Create: * Name: annotations * Build system: Gradle ![Creating a new module](images/ksp-new-module.png) 4. In the module, create a `HelloWorldAnnotation.kt` file and declare `HelloWorldAnnotation`: ```KOTLIN // annotations/src/main/kotlin/com/example/annotations/HelloWorldAnnotation.kt package com.example.annotations annotation class HelloWorldAnnotation ``` ### Create and register a processor 1. Create a `processor` module at the root of the project. 2. Add the KSP API and the annotation you declared as dependencies in the module's `build.gradle(.kts)` file: Kotlin: ```KOTLIN // processor/build.gradle.kts plugins { kotlin("jvm") } dependencies { implementation(project(":annotations")) implementation("com.google.devtools.ksp:symbol-processing-api:2.3.12") } ``` Groovy: ```GROOVY // processor/build.gradle plugins { id 'org.jetbrains.kotlin.jvm' } dependencies { implementation project(':annotations') implementation 'com.google.devtools.ksp:symbol-processing-api:2.3.12' } ``` 3. In the processor module, create a new `HelloWorldProcessor.kt` file and add the following code: ```KOTLIN // processor/src/main/kotlin/HelloWorldProcessor.kt class HelloWorldProcessor(val codeGenerator: CodeGenerator, val greeting: String) : SymbolProcessor { // 1️⃣ process() function override fun process(resolver: Resolver): List { resolver .getSymbolsWithAnnotation("com.example.annotations.HelloWorldAnnotation") .filter { it.validate() } .filterIsInstance() .forEach { it.accept(HelloWorldVisitor(), Unit) } return emptyList() } // 2️⃣ Visitor inner class HelloWorldVisitor : KSVisitorVoid() { override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) { createNewFileFrom(function).use { file -> file.write( """ fun helloWorld() { println("$greeting from function generated by KSP") } """.trimIndent() ) } } } // 3️⃣ createNewFileFrom() function private fun createNewFileFrom(function: KSFunctionDeclaration): OutputStream { return codeGenerator.createNewFile( dependencies = createDependencyOn(function), packageName = "", fileName = "GeneratedHelloWorld" ) } // 3️⃣ createDependencyOn() function private fun createDependencyOn(function: KSFunctionDeclaration): Dependencies { return Dependencies(aggregating = false, function.containingFile!!) } } // Writes a string to the OutputStream fun OutputStream.write(string: String) { this.write(string.toByteArray()) } ``` Add the imports that are suggested by the IDE. Make sure to import `Resolver` and `Dependencies` from the `com.google.devtools.ksp.processing` package. Alternatively, copy these lines to the top of `HelloWorldProcessor.kt`: ```KOTLIN // processor/src/main/kotlin/HelloWorldProcessor.kt import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSVisitorVoid import com.google.devtools.ksp.validate import java.io.OutputStream ``` Let's go through the code: * 1️⃣ The `process()` function contains the main logic of the processor. It finds symbols annotated with `HelloWorldAnnotation`, skips invalid ones, and visits each function declaration with `HelloWorldVisitor`. The `process()` function returns a list of unprocessed symbols to process in a later round. In this example, it safely returns `emptyList()`. For more information, see [Multiple-round processing](ksp-multi-round.html). * 2️⃣ Processors use visitors to traverse symbols and inspect declarations. Inside the `HelloWorldProcessor` class, the `HelloWorldVisitor` class is the visitor. Since `HelloWorldAnnotation` is only used on functions, the visitor overrides only `visitFunctionDeclaration()`. The generated `helloWorld()` function prints the `greeting` that the processor receives from its provider. Tip: `KSVisitorVoid` is one of the visitor classes provided by KSP that you can override and adapt. You can also create your own visitor by implementing the [KSVisitor<D, R> interface](https://github.com/google/ksp/blob/main/api/src/main/kotlin/com/google/devtools/ksp/symbol/KSVisitor.kt). * 3️⃣ `createNewFileFrom()` creates the file where the processor writes the generated code. `createDependencyOn()` makes the output file depend on the source file where the annotation is used. Tip: To learn more about how KSP creates and manages files, see the source code of the [CodeGenerator interface](https://github.com/google/ksp/blob/main/api/src/main/kotlin/com/google/devtools/ksp/processing/CodeGenerator.kt). 4. Create a `HelloWorldProcessorProvider.kt` file. In it, declare a `HelloWorldProcessorProvider` class that implements the `SymbolProcessorProvider` interface: ```KOTLIN // processor/src/main/kotlin/HelloWorldProcessorProvider.kt import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider class HelloWorldProcessorProvider : SymbolProcessorProvider { override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor { // Falls back to "Hello world" if the greeting option isn't set val greeting = environment.options["greeting"] ?: "Hello world" return HelloWorldProcessor(environment.codeGenerator, greeting) } } ``` The provider reads the `greeting` processor option from `SymbolProcessorEnvironment.options` and passes it to the processor. This lets users of your processor change the greeting without changing the processor code. For more information, see [Pass options to processors](#pass-options-to-processors). 5. Register the processor provider. In the `resources/META-INF/services` directory, create a `com.google.devtools.ksp.processing.SymbolProcessorProvider` file and add the provider's fully qualified name: ```TEXT # processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider HelloWorldProcessorProvider ``` ### Use your processor Now you are ready to test your processor. Follow these steps to create a client module and have your processor generate code based on an annotated element: 1. Create a module called `app` at the root of your project. 2. In the module's `build.gradle(.kts)` file: * Add the KSP plugin to the `plugins {}` block. * Add your processor and annotation to the `dependencies {}` block. For example: Kotlin: ```KOTLIN // app/build.gradle.kts plugins { kotlin("jvm") id("com.google.devtools.ksp") } dependencies { implementation(project(":annotations")) ksp(project(":processor")) } ``` Groovy: ```GROOVY // app/build.gradle plugins { id 'org.jetbrains.kotlin.jvm' id 'com.google.devtools.ksp' } dependencies { implementation project(':annotations') ksp project(':processor') } ``` 3. In the project-level `settings.gradle(.kts)` file, make sure to include all submodules: Kotlin: ```KOTLIN // settings.gradle.kts include("annotations") include("app") include("processor") ``` Groovy: ```GROOVY // settings.gradle include 'annotations' include 'app' include 'processor' ``` 4. In the `app` module, create a `Main.kt` file and add the following code: ```KOTLIN // app/src/main/kotlin/Main.kt import com.example.annotations.HelloWorldAnnotation @HelloWorldAnnotation fun main() { helloWorld() } ``` Note: The `main()` function calls `helloWorld()`, even though this function doesn't exist yet. Your IDE highlights `helloWorld()` as an unresolved reference. This is an expected behavior: your processor generates the `helloWorld()` function during the build. 5. Run the program. You see the output of the `helloWorld()` function in your console: ```TEXT Hello world from function generated by KSP ``` The processor generates the code in the `GeneratedHelloWorld.kt` file: ```TEXT app/build/generated/ksp/main/kotlin/GeneratedHelloWorld.kt ``` ### Explore the project structure Your project's final file structure should look like this. You might have additional files and directories: ```TEXT . ├── app │ ├── build.gradle.kts │ └── src │ └── main │ └── kotlin │ └── Main.kt ├── annotations │ ├── build.gradle.kts │ └── src │ └── main │ └── kotlin │ └── com │ └── example │ └── annotations │ └── HelloWorldAnnotation.kt ├── processor │ ├── build.gradle.kts │ └── src │ └── main │ ├── kotlin │ │ ├── HelloWorldProcessor.kt │ │ └── HelloWorldProcessorProvider.kt │ └── resources/META-INF/services │ └── com.google.devtools.ksp.processing.SymbolProcessorProvider ├── build.gradle.kts └── settings.gradle.kts ``` ## Pass options to processors Some processors accept options that change how they generate code. To pass options to a processor, add a `ksp {}` block to the `build.gradle(.kts)` file of the module that uses the processor and call `arg()` for each option. KSP passes the same options to every processor in the module. The processor from the [Create your own processor](#create-your-own-processor) section accepts a `greeting` option. To change the greeting: 1. In the `app` module's `build.gradle(.kts)` file, add the `ksp {}` block and set the `greeting` option: Kotlin: ```KOTLIN // app/build.gradle.kts ksp { arg("greeting", "Hi") } ``` Groovy: ```GROOVY // app/build.gradle ksp { arg('greeting', 'Hi') } ``` 2. Run the program again. The output shows the new greeting: ```TEXT Hi from function generated by KSP ``` ## What's next? * Explore the [full code for this example](https://github.com/google/ksp/tree/main/examples/hello-world) in the KSP repository. * Find more complex examples in [the KSP repository](https://github.com/google/ksp/tree/main/examples). * Learn [how KSP represents the code](ksp-kotlin-model.html). * Browse the list of [libraries that support KSP](ksp-overview.html#supported-libraries).