附加注释类型的扩展函数

Hei*_*ich 6 annotations kotlin kotlin-extension

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

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

替代形式:

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

这将对应于以下静态功能:

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

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

在一个侧面说明:同样的问题也适用于@IntDef,@StringDef,@[resource type]Res以及.

Kir*_*man 20

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

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

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

  • 这还有效吗?我正在这样做,但是使用布局res,字符串res,即使使用负数,也没有警告。 (7认同)
  • 不,`@ ColorInt`是一个特定于android的注释,由Lint评估.Lint支持Kotlin代码,当你在没有注释的int上调用方法时,你应该得到一个警告,但你仍然可以调用该方法. (2认同)
  • @AKSH这似乎是一个错误,应该在1.2.40中修复:https://youtrack.jetbrains.com/issue/KT-21696 (2认同)