13.3 Micronaut for Kotlin

The Command Line Interface for Micronaut includes special support for Kotlin. To create a Kotlin application use the kotlin lang option. For example:

Create a Micronaut Kotlin application

  1. $ mn create-app hello-world --lang kotlin

Support for Kotlin in Micronaut is built upon the Kapt compiler plugin, which includes support for Java annotation processors. To use Kotlin in your Micronaut application, add the proper dependencies to configure and run kapt on your kt source files. Kapt creates Java “stub” classes for your Kotlin classes, which can then be processed by Micronaut’s Java annotation processor. The stubs are not included in the final compiled application.

Learn more about kapt and its features from the official documentation.

The Micronaut annotation processors are declared in the kapt scope when using Gradle. For example:

Example build.gradle

  1. dependencies {
  2. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion" (1)
  3. compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
  4. kapt "io.micronaut:micronaut-inject-java" (2)
  5. kaptTest "io.micronaut:micronaut-inject-java" (3)
  6. ...
  7. }
1Add the Kotlin standard libraries
2Add the micronaut-inject-java dependency under the kapt scope, so classes in src/main are processed
3Add the micronaut-inject-java dependency under the kaptTest scope, so classes in src/test are processed.

With a build.gradle file similar to the above, you can now run your Micronaut application using the run task (provided by the Application plugin):

  1. $ ./gradlew run

An example controller written in Kotlin can be seen below:

src/main/kotlin/example/HelloController.kt

  1. package example
  2. import io.micronaut.http.annotation.*
  3. @Controller("/")
  4. class HelloController {
  5. @Get("/hello/{name}")
  6. fun hello(name: String): String {
  7. return "Hello $name"
  8. }
  9. }