Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Android Support typedef annotations in kotlin?

Tags:

android

kotlin

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?

like image 686
curioushikhov Avatar asked Mar 13 '16 21:03

curioushikhov


People also ask

How to use annotation class in android?

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.

What is android annotation?

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.


1 Answers

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 vals.

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 Ints.

like image 163
Ronald Martin Avatar answered Oct 12 '22 01:10

Ronald Martin