Code generate a couple of functions at compile-time — HOW?

I’m wondering what’s the current state of “compile-time code generation”. What I need is basically an annotation which, if applied, will generate a couple of boilerplate methods for that object/class.

For example:

class Foo(
    val i: Int,
    val s: String,
    val b: Boolean)

This is just an example, I know that data classes have hashCode implementation already. But my case is very similar and I would like to generate a couple of boilerplate methods if the annotation is present.

Where are we currently? Is this supported? Where can I check for a minimal setup to make it work?

I suspect that Moshi and Kotlin Serialization are already doing something like this.

Thank you

Have a look at Kotlin Poet.

Kotlin Poet seems like a useless templating engine which is exactly what I don’t need. I need generation at compile time.

If you are targeting the JVM you should look into kapt which is the kotlin version of java anotation processing. If you need to add real member functions to classes or target mpp/js/native you have to use compiler plugins which is still an kotlin internal featuer. However the arrow guys have a framework that should allow you to write your own plugins anyways. Not sure how stable it is. Last time I experimented it (about a year ago) it was still in an early beta stage.

1 Like