Kotlin annotations on delegated properties

Viewed 9598

In Kotlin, is there a way to define an annotation on a delegated property (ex: lazy)?

class MyActivity: Activity() {

    @ColorInt
    val textColor: Int by lazy { ContextCompat.getColor(this, R.color.someColor) }
    ...

The IDE throws an error at the @ColorInt annotation:

This annotation is not applicable to target 'member property with delegate'

2 Answers

If annotating the getter is enough for you, you can use annotation use-site target, @get:ColorInt:

@get:ColorInt
val textColor: Int by lazy { ... }

You can annotate the delegate with @delegate.

@delegate:ColorInt
val textColor: Int by lazy { ... }

From the documentation:

  • delegate (the field storing the delegate instance for a delegated property).
Related