Kotlin 中的嵌套注释

Mic*_*ael 2 annotations nested kotlin

在 Java 中,可以像这样创建嵌套注释:

public @interface InnerInnotation {
  String value();
}

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

annotation class InnerAnnotation(val value: String)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在 Kotlin 中做同样的事情时,我得到一个编译错误:

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

但是,单个实例注释字段工作正常:

annotation class OuterAnnotation(
  val value: InnerAnnotation = InnerAnnotation("Hello World")
)
Run Code Online (Sandbox Code Playgroud)

有没有办法用嵌套的注释数组字段定义注释并为此字段指定默认值?

eva*_*oly 5

如果您不在@嵌套注释上使用,这将起作用。据我阅读并与开发人员讨论,这是嵌套注释的预期语法。感觉不一致,我希望他们改变它,但如此接近 1.0,希望很低。

  • 但我不在嵌套注释上使用 `@`。 (2认同)