2017-05-28 66 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