如何在 Kotlin 注解中编写成员?

Шах*_*Шах 2 java annotations kotlin

我有下一个 Java 注释:

@Retention(RetentionPolicy.RUNTIME)
@MapKey
@interface ViewModelKey {
    Class<? extends ViewModel> value();
}
Run Code Online (Sandbox Code Playgroud)

为了将其转换为 Kotlin 注释,我将其重写如下:

@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey {
    fun value(): Class<out ViewModel> {}
}
Run Code Online (Sandbox Code Playgroud)

但有一个错误:Members are not allowed in annotation class

如果不允许成员,如何在 Kotlin 中转换 Java 注释?

Ren*_*ene 5

在 Kotlin 中,您必须在注释中定义属性而不是函数:

@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅https://kotlinlang.org/docs/reference/annotations.html