注释类型的扩展函数
Extension functions on annotated types
是否可以像这样在带注释的类型上定义 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
。
是的,你可以。使用以下语法:
@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
是否可以像这样在带注释的类型上定义 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
。
是的,你可以。使用以下语法:
@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