3

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 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.