2017-05-28 80 views
2

是否可以像这样在注释类型上定义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) 
} 

这将对应于以下静态funtion:

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

我不认为这是可能的但使用科特林,但它是可能的在后来的Kotlin版本中添加该功能?

在一个侧面说明: 同样的问题适用于@IntDef@StringDef@[resource type]Res为好。

+0

zsmb13有一个好点的解释,这可能会导致一些问题与具有相同签名一倍方法。无论如何,这可以通过为该函数注释一个不同的JVM方法名来解决。 – Heinrich

回答

6

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

@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

+0

太棒了!我想IntelliJ会自动隐藏未注释的@ @ ColorInt方法的扩展函数,对吧? – Heinrich

+1

不,'@ ColorInt'是由Lint评估的一个特定于android的注释。 Lint支持Kotlin代码,当您在未注释的int调用该方法时应该会收到警告,但您仍然可以调用该方法。 –

+0

这将如预期。 – Heinrich