I develop Android applications and often use annotations as compile time parameter checks, mostly android's support annotations.
Example in java code:
public class Test { @IntDef({Speed.SLOW,Speed.NORMAL,Speed.FAST}) public @interface Speed { public static final int SLOW = 0; public static final int NORMAL = 1; public static final int FAST = 2; } @Speed private int speed; public void setSpeed(@Speed int speed) { this.speed = speed; } }
I don't want to use enums because of their performance issues in Android. The automatic converter to kotlin just generates invalid code. How do I use the @IntDef
annotation in kotlin?
To enable annotations in your project, add the support-annotations dependency to your library or app. Any annotations you add then get checked when you run a code inspection or lint task.
Android Annotations is an annotation-driven framework that allows you to simplify the code in your applications and reduces the boilerplate of common patterns, such as setting click listeners, enforcing ui/background thread executions, etc.
Edit: In case you miss the comments on the question or this answer, it's worth noting that the following technique compiles, but does not create the compile-time validation you would get in Java (which partially defeats the purpose of doing this). Consider using an enum class instead.
It is actually possible to use the @IntDef
support annotation by defining your values outside of the annotation class as const val
s.
Using your example:
import android.support.annotation.IntDef public class Test { companion object { @IntDef(SLOW, NORMAL, FAST) @Retention(AnnotationRetention.SOURCE) annotation class Speed const val SLOW = 0L const val NORMAL = 1L const val FAST = 2L } @Speed private lateinit var speed: Long public fun setSpeed(@Speed speed: Long) { this.speed = speed } }
Note that at this point the compiler seems to require the Long
type for the @IntDef
annotation instead of actual Int
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With