Custom compiler annotations


#1

Hi,

Is there a way of creating a custom annotation like data? I.e. having an annotation that generates some code and my own code can use, and (as bonus) that IDEA won’t mark as invalid?

If that’s not possible, does accessing Kotlin annotations at runtime have the same performance implications as with Java? (which uses reflection, which means it’s bad in places like Android)

Thanks!


#2

Annotations are just standard JVM entities and doesn't differ much from those generated by Java compiler. As of now, there is no special facility to create custom code transformations or generators in the language. You can use annotation processing to generate some code based on annotations. Or you can write compiler plugin, which is hard and unsupported, but may be much more powerful.


#3

Thank you!

Is there any planned support to create our own “compiler” annotations? If I understand it correctly, using that “kapt” tool won’t make IDEA pick anything that it generates because it needs a separate step.


#4

No, we don't have any specific plans right now. You can take a look at plugin to generate Android properties from .xml, https://github.com/JetBrains/kotlin/tree/master/plugins

Out of curiosity, what kind of code generation do you have in mind?


#5

Thanks, will take a look.

Right now, it might be a bit overkill, but I’ve created a few annotations that I use to mark some classes and store metadata about them (things like “speed” or “altitude”). At runtime, I get the annotations using reflection and get those values. It will be nice if I can instead get the values using getters, like the data annotation does.

I can also obviously move all this annotation metadata to normal fields, but the definition of the metadata was very nice to read, at least in Java.

Thank you for your responses :slight_smile:


#6

You can try to use companion objects instead. Something like this:

 
data class Metadata(val speed : Double, val altitude: Double)

class LandRover {
  companion object {
  val metadata = Metadata(120.0, 0.0)
  }
}

fun use() {
  println(LandRover.metadata.altitude)
}


#7

Well, that's more verbose than the annotations, but interesting nonetheless :). I'll read about those companion objects to see what they can do, thanks!