KotlinPoet 1.0 is here!

KotlinPoet is a collection of Kotlin API that makes generating .kt files easy. It’s inspired by JavaPoet, a Java code generation library…

KotlinPoet is a collection of Kotlin API that makes generating .kt files easy. It’s inspired by JavaPoet, a Java code generation library, which powers a number of widely used frameworks, such as Dagger.

KotlinPoet has been around for over a year and is used by a number of popular libraries, such as Moshi and SQLDelight. It’s sweet, it’s battle-tested, it’s ready for prime-time, and today we’re announcing KotlinPoet 1.0! 🎉

Hello World, KotlinPoet! 👋

Here’s a HelloWorld file from KotlinPoet’s README page:

class Greeter(val name: String) {
    fun greet() {
        println("Hello, $name")
    }
}

fun main(vararg args: String) {
    Greeter(args[0]).greet()
}

And this is the code to generate it with KotlinPoet:

val greeterClass = ClassName("", "Greeter")
val file = FileSpec.builder("", "HelloWorld")
    .addType(TypeSpec.classBuilder("Greeter")
        .primaryConstructor(FunSpec.constructorBuilder()
            .addParameter("name", String::class)
            .build())
        .addProperty(PropertySpec.builder("name", String::class)
            .initializer("name")
            .build())
        .addFunction(FunSpec.builder("greet")
            .addStatement("println(%P)", "Hello, \$name")
            .build())
        .build())
    .addFunction(FunSpec.builder("main")
        .addParameter("args", String::class, VARARG)
        .addStatement("%T(args[0]).greet()", greeterClass)
        .build())
    .build()

file.writeTo(System.out)

A few things to point out here:

  • Specs. KotlinPoet models the file structure using a set of Spec classes, each representing a specific Kotlin construct. Each Spec has an associated Builder class that makes it simple to configure the Spec. All Specs should ultimately be added to a FileSpec, which represents a .kt file.

  • Types. Referencing types is easy, as most of KotlinPoet’s API is optimized to work with Kotlin’s KClass. There are also a few classes that allow you to introduce your own types, such as ClassName, LambdaTypeName, ParameterizedTypeName and others.

  • Custom format specifiers. KotlinPoet comes with a number of format specifiers, which work similarly to %s and %d. For instance, %S will turn its argument into a double-quoted String, and %L can take an entire Spec as an argument.

  • Output. Once you’re done configuring the Specs, call writeTo() on the FileSpec to output the model into the selected destination, supported options include kotlin.Appendable, java.io.File and java.nio.file.Path.

KotlinPoet can generate extension and single-expression functions, nullable types, data classes, expect/actual definitions and much much more! To learn more about KotlinPoet API, check out the KDoc and README.

It’s codegen time!

Table Of Contents
View More Articles ›