Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin annotations on delegated properties

Tags:

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'

like image 517
triad Avatar asked Nov 10 '17 01:11

triad


People also ask

What is delegated properties in Kotlin?

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.

How does Kotlin delegate work?

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.

Which is is the Kotlin keyword for delegation?

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.


2 Answers

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).
like image 108
mkobit Avatar answered Sep 19 '22 07:09

mkobit


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

@get:ColorInt val textColor: Int by lazy { ... } 
like image 22
hotkey Avatar answered Sep 17 '22 07:09

hotkey