Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested annotations in Kotlin

In Java it's possible to create nested annotations like this one:

public @interface InnerInnotation {
  String value();
}

public @interface OuterAnnotation {
  InnerAnnotation[] value() default {
    @InnerAnnotation("Hello"),
    @InnerAnnotation("World")
  }
}

annotation class InnerAnnotation(val value: String)

But when I'm trying to do the same thing in Kotlin, I get a compilation error:

annotation class OuterAnnotation(
  // Next line doesn't compile: "Annotation class cannot be instantiated"
  val value: Array<InnerAnnotation> = arrayOf(InnerAnnotation("Test"))
)

However a single instance annotation field works fine:

annotation class OuterAnnotation(
  val value: InnerAnnotation = InnerAnnotation("Hello World")
)

Is there a way to define an annotation with a nested annotation array field and specify a default value for this field?

like image 424
Michael Avatar asked Aug 05 '26 07:08

Michael


1 Answers

This works if you don't use @ on the nested annotations. As far as I've read and talked to the devs about, this is the intended syntax for nested annotations. It feels inconsistent and I hope they change it but being so close to 1.0, hopes are low.

like image 129
evanchooly Avatar answered Aug 08 '26 16:08

evanchooly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!