Restricting values in parameters via annotations Kotlin

Viewed 287

I was testing Kotlin annotations and wasn't able to get this seemingly simple code to work

This is my simple annotation

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

Now I am assuming that if I decorate a value parameter with @OnlyOneTwo , that method would raise a compile error if I give it a value like 5 .

I am using this annotation like this

fun onlyTakesOneTwos(@OnlyOneTwo input:Int){

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

I remember in Java it used to throw an error.

1 Answers

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 in Kotlin to provide suggestions but other values won't give you a compile error. Also with ART, mem footprint for enums are not a big deal, this was also covered in Google IO 2018 while talking about ART https://youtu.be/IrMw7MEgADk?t=855

Related