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'
A delegate is just a class that provides the value for a property and handles its changes. This allows us to move, or delegate, the getter-setter logic from the property itself to a separate class, letting us reuse this logic.
Kotlin Vocabulary: Delegates Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate. The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.
Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.
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).
If annotating the getter is enough for you, you can use annotation use-site target, @get:ColorInt
:
@get:ColorInt val textColor: Int by lazy { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With