blog podcast

Kotlin Annotation Processing

When Kotlin was created it had the advantage compared to Java that it didn’t need to support all of the legacy syntax. This advantage, I believe, enabled the developers to bake in necessary modern features into the language directly instead of how it’s been done in Java a lot, with annotations and black magic. For this reason Kotlin has had less need for annotations than Java, it’s an efficient language already.

Sometimes though you need annotations. Often you will be using libraries that are written in Java and for the magic to work you might need to add some annotations into your code. The black magic kind of annotations are processed at compile time and start doing all kind of weird stuff with your code. Lombok is a good example of this. Another example is the one that I was having problems with, the protobuf generator found in the infinispan project.

Protobuf is a serialization method developed at google that’s more concise than JSON, but still relatively flexible in terms of changing the schema. Infinispan uses this per default to serialize and deserialize entities that you store in your cache. All you need to do is mark your entity classes with the right annotations and it all works out of the box… Well if you use Java at least. With Kotlin you have an issue, because these annotations are black magic annotations and they need to be run at compile time.

You’ll be happy to learn that also Kotlin can do black magic though. There a plugin called kapt (and it’s even had time to be deprecated for another project). By importing this library and using

plugins {
    kotlin("kapt") version "1.6.10"

in Gradle you can get annotation processing to work. An example for how to do this in infinispan can be found here.