简体   繁体   中英

How to write a member in Kotlin annotation?

I have the next Java annotation:

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

To convert it in Kotlin annotation I have rewritten it as below:

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

But there is an error: Members are not allowed in annotation class .

If members aren't allowed how can I convert Java annotation in Kotlin?

In Kotlin you have to define properties and not functions in annotations:

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

See https://kotlinlang.org/docs/reference/annotations.html for details.

It might be a "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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM