Denis Steinman
Denis Steinman

Reputation: 7809

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?

Upvotes: 2

Views: 2131

Answers (2)

Rene
Rene

Reputation: 6258

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.

Upvotes: 5

ust
ust

Reputation: 171

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

Upvotes: 1

Related Questions