kapt compiler plugin
Annotation processors (see JSR 269) are supported in Kotlin with the kapt compiler plugin.
In a nutshell, kapt helps you use libraries like Dagger and Data Binding in your Kotlin projects by enabling Java-based annotation processing.
Use in Gradle
To use kapt in Gradle, follow these steps:
Apply the
kapt
Gradle plugin in your build script filebuild.gradle(.kts)
:plugins { kotlin("kapt") version "2.2.0" }plugins { id "org.jetbrains.kotlin.kapt" version "2.2.0" }Add the respective dependencies using the
kapt
configuration in thedependencies {}
block:dependencies { kapt("groupId:artifactId:version") }dependencies { kapt 'groupId:artifactId:version' }If you previously used the Android support for annotation processors, replace usages of the
annotationProcessor
configuration withkapt
. If your project contains Java classes,kapt
will also take care of them.If you use annotation processors for your
androidTest
ortest
sources, the respectivekapt
configurations are namedkaptAndroidTest
andkaptTest
. Note thatkaptAndroidTest
andkaptTest
extendkapt
, so you can provide thekapt
dependency, and it will be available both for production sources and tests.
Annotation processor arguments
Use the arguments {}
block in your build script file build.gradle(.kts)
to pass arguments to annotation processors:
Gradle build cache support
The kapt annotation processing tasks are cached in Gradle by default. However, annotation processors can run arbitrary code, which may not reliably transform task inputs into outputs, or may access and modify files that Gradle doesn't track. If the annotation processors used in the build cannot be properly cached, you can disable caching for kapt entirely by specifying the useBuildCache
property in the build script. This helps prevent false-positive cache hits for the kapt tasks:
Improve the speed of builds that use kapt
Run kapt tasks in parallel
To improve the speed of builds that use kapt, you can enable the Gradle Worker API for kapt tasks. Using the Worker API lets Gradle run independent annotation processing tasks from a single project in parallel, which in some cases significantly decreases the execution time.
When you use the custom JDK home feature in the Kotlin Gradle plugin, kapt task workers use only process isolation mode. Note that the kapt.workers.isolation
property is ignored.
If you want to provide additional JVM arguments for a kapt worker process, use the input kaptProcessJvmArgs
of the KaptWithoutKotlincTask
:
Caching for annotation processors' classloaders
Caching for annotation processors' classloaders helps kapt perform faster if you run many Gradle tasks consecutively.
To enable this feature, use the following properties in your gradle.properties
file:
If you run into any problems with caching for annotation processors, disable caching for them:
Measure performance of annotation processors
To get performance statistics on the annotation processors execution, use the -Kapt-show-processor-timings
plugin option. An example output:
You can dump this report into a file with the plugin option -Kapt-dump-processor-timings
(org.jetbrains.kotlin.kapt3:dumpProcessorTimings
). The following command will run kapt and dump the statistics to the ap-perf-report.file
file:
Measure the number of files generated with annotation processors
The kapt
Gradle plugin can report statistics on the number of generated files for each annotation processor.
This helps track whether any unused annotation processors are included in the build. You can use the generated report to find modules that trigger unnecessary annotation processors and update the modules to avoid that.
To enable statistics reporting:
Set the
showProcessorStats
property value totrue
in yourbuild.gradle(.kts)
:// build.gradle.kts kapt { showProcessorStats = true }Set the
kapt.verbose
Gradle property totrue
in yourgradle.properties
:# gradle.properties kapt.verbose=true
The statistics appear in the logs with the info
level. You can see the Annotation processor stats:
line followed by statistics on the execution time of each annotation processor. After these lines, there is the Generated files report:
line followed by statistics on the number of generated files for each annotation processor. For example:
Compile avoidance for kapt
To improve the times of incremental builds with kapt, it can use the Gradle compile avoidance. With compile avoidance enabled, Gradle can skip annotation processing when rebuilding a project. Particularly, annotation processing is skipped when:
The project's source files are unchanged.
The changes in dependencies are ABI-compatible. For example, the only changes are in method bodies.
However, compile avoidance can't be used for annotation processors discovered in the compile classpath since any changes in them require running the annotation processing tasks.
To run kapt with compile avoidance:
Add the annotation processor dependencies to the
kapt*
configurations manually.Turn off the discovery of annotation processors in the compile classpath in the
gradle.properties
file:# gradle.properties kapt.include.compile.classpath=false
Incremental annotation processing
kapt supports incremental annotation processing by default. Currently, annotation processing can be incremental only if all annotation processors being used are incremental.
To disable incremental annotation processing, add this line to your gradle.properties
file:
Note that incremental annotation processing requires incremental compilation to be enabled as well.
Inherit annotation processors from superconfigurations
You can define a common set of annotation processors in a separate Gradle configuration as a superconfiguration and extend it further in kapt-specific configurations for your subprojects.
As an example, for a subproject using Dagger, in your build.gradle(.kts)
file, use the following configuration:
In this example, the commonAnnotationProcessors
Gradle configuration is your common superconfiguration for annotation processing that you want to be used for all your projects. You use the extendsFrom()
method to add commonAnnotationProcessors
as a superconfiguration. kapt sees that the commonAnnotationProcessors
Gradle configuration has a dependency on the Dagger annotation processor. Therefore, kapt includes the Dagger annotation processor in its configuration for annotation processing.
Java compiler options
kapt uses Java compiler to run annotation processors.
Here is how you can pass arbitrary options to javac:
Non-existent type correction
Some annotation processors (such as AutoFactory
) rely on precise types in declaration signatures. By default, kapt replaces every unknown type (including types for the generated classes) to NonExistentClass
, but you can change this behavior. Add the option to the build.gradle(.kts)
file to enable error type inferring in stubs:
Use in Maven
Add an execution of the kapt
goal from kotlin-maven-plugin before compile
:
To configure the level of annotation processing, set one of the following as the aptMode
in the <configuration>
block:
stubs
– only generate stubs needed for annotation processing.apt
– only run annotation processing.stubsAndApt
– (default) generate stubs and run annotation processing.
For example:
Use in IntelliJ build system
kapt is not supported for IntelliJ IDEA's own build system. Launch the build from the "Maven Projects" toolbar whenever you want to re-run the annotation processing.
Use in CLI
kapt compiler plugin is available in the binary distribution of the Kotlin compiler.
You can attach the plugin by providing the path to its JAR file using the Xplugin
kotlinc option:
Here is a list of the available options:
sources
(required): An output path for the generated files.classes
(required): An output path for the generated class files and resources.stubs
(required): An output path for the stub files. In other words, some temporary directory.incrementalData
: An output path for the binary stubs.apclasspath
(repeatable): A path to the annotation processor JAR. Pass as manyapclasspath
options as the number of JARs that you have.apoptions
: A base64-encoded list of the annotation processor options. See AP/javac options encoding for more information.javacArguments
: A base64-encoded list of the options passed to javac. See AP/javac options encoding for more information.processors
: A comma-specified list of annotation processor qualified class names. If specified, kapt does not try to find annotation processors inapclasspath
.verbose
: Enable verbose output.aptMode
(required)stubs
– only generate stubs needed for annotation processing.apt
– only run annotation processing.stubsAndApt
– generate stubs and run annotation processing.
correctErrorTypes
: For more information, see Non-existent type correction. Disabled by default.dumpFileReadHistory
: An output path to dump for each file a list of classes used during annotation processing.
The plugin option format is: -P plugin:<plugin id>:<key>=<value>
. Options can be repeated.
An example:
Generate Kotlin sources
kapt can generate Kotlin sources. Just write the generated Kotlin source files to the directory specified by processingEnv.options["kapt.kotlin.generated"]
, and these files will be compiled together with the main sources.
Note that kapt does not support multiple rounds for the generated Kotlin files.
AP/Javac options encoding
apoptions
and javacArguments
CLI options accept an encoded map of options.
Here is how you can encode options by yourself:
Keep Java compiler's annotation processors
By default, kapt runs all annotation processors and disables annotation processing by javac. However, you may need some of javac's annotation processors working (for example, Lombok).
In the Gradle build file, use the option keepJavacAnnotationProcessors
:
If you use Maven, you need to specify concrete plugin settings. See this example of settings for the Lombok compiler plugin.