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, 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:

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!