Is it possible to define a Kotlin extension function on a annotated type like this?
@ColorInt
fun @ColorInt Int.darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
Alternative form:
@ColorInt
fun (@ColorInt Int).darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
That would correspond to the following static funtion:
@ColorInt
fun darken(@ColorInt color: Int): Int {
return ColorUtils.blendARGB(color, Color.BLACK, 0.2f)
}
I don't think that's possible yet using Kotlin, but would it be possible to add that feature in later Kotlin versions?
On a side note:
The same question applies to @IntDef
, @StringDef
, @[resource type]Res
as well.
Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.
Kotlin extensions provide the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. These extensions basically add some functionality in an existing class without extending the class.
Instantiation. In Java, an annotation type is a form of an interface, so you can implement it and use an instance. As an alternative to this mechanism, Kotlin lets you call a constructor of an annotation class in arbitrary code and similarly use the resulting instance.
The variable name is known as the receiver of the call because it's the variable that the extension function is acting upon. In this case, the block passed to let() is only evaluated if the variable name was non-null.
Yes you can. Use the following syntax:
@ColorInt
fun @receiver:ColorInt Int.darken(): Int {
return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}
More about annotation use-site targets: http://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets
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