Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension functions on annotated types

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.

like image 707
Jan Heinrich Reimer Avatar asked May 28 '17 21:05

Jan Heinrich Reimer


People also ask

What are extension functions?

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.

What are extension methods in Kotlin?

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.

What is a type annotation in Kotlin?

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.

What is the receiver in an extension function in Kotlin?

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.


1 Answers

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

like image 69
Kirill Rakhman Avatar answered Oct 13 '22 20:10

Kirill Rakhman