簡體   English   中英

通過注解限制參數值 Kotlin

[英]Restricting values in parameters via annotations Kotlin

我正在測試 Kotlin 注釋,但無法讓這個看似簡單的代碼工作

這是我的簡單注釋

@IntDef(1,2)
@Target(
    AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class OnlyOneTwo

現在我假設如果我用@OnlyOneTwo裝飾一個 value 參數,如果我給它一個像5這樣的值,該方法會引發編譯錯誤。

我正在使用這樣的注釋

fun onlyTakesOneTwos(@OnlyOneTwo input:Int){

}
onlyTakesOneTwos(6) // shouldn't this throw a compile error ?

我記得在 Java 中它曾經拋出錯誤。

Firstly, it is not Kotlin compiler which checks for this type of annotation errors, Android Lint does, also this might work and preferred over enums in Java , but in Kotlin , the only way to do these are using enums , You can still use @IntDef中的Kotlin提供建議,但其他值不會給您編譯錯誤。 同樣對於 ART,枚舉的內存占用也不是什么大問題,Google IO 2018 在談論ART https://youtu.be/IrMw7MEgADk?t=855時也對此進行了介紹

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM