21

是否可以在这样的带注释类型上定义 Kotlin 扩展函数?

@ColorInt
fun @ColorInt Int.darken(): Int {
    return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}

替代形式:

@ColorInt
fun (@ColorInt Int).darken(): Int {
    return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}

这将对应于以下静态函数:

@ColorInt
fun darken(@ColorInt color: Int): Int {
    return ColorUtils.blendARGB(color, Color.BLACK, 0.2f)
}

我认为使用 Kotlin 尚不可能,但是否可以在以后的 Kotlin 版本中添加该功能?

附带说明:同样的问题也适用于@IntDef, @StringDef, @[resource type]Res

4

1 回答 1

44

是的你可以。使用以下语法:

@ColorInt
fun @receiver:ColorInt Int.darken(): Int {
    return ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
}

有关注释使用站点目标的更多信息:http: //kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets

于 2017-05-29T06:36:44.810 回答