如何在 Kotlin 注解中写一个成员?

How to write a member in Kotlin annotation?

我有下一个 Java 注释:

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

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

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

但是出现错误:Members are not allowed in annotation class.

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

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

@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)

详情见https://kotlinlang.org/docs/reference/annotations.html

可能是 "KClass";

@Retention(RetentionPolicy.RUNTIME)
@MapKey
internal annotation class ViewModelKey(val value: KClass<out ViewModel>)

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect/-k-class/index.html