Michael
Michael

Reputation: 54705

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?

Upvotes: 2

Views: 2620

Answers (2)

evanchooly
evanchooly

Reputation: 6233

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.

Upvotes: 6

Alexander Udalov
Alexander Udalov

Reputation: 32776

This is a bug in the Kotlin compiler, it should be allowed. Thanks for the report! I've created an issue: https://youtrack.jetbrains.com/issue/KT-10136

I'm not aware of any workaround though, except rewriting OuterAnnotation in Java.

Upvotes: 3

Related Questions