Search code examples
annotationskotlinkotlin-extension

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.


Solution

  • 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