How to use Android Support typedef annotations in kotlin?

Viewed 14780

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?

4 Answers

Update:

Forget @IntDef and @StringDef, Now, with ART, you can use enums instead.

From the official GoogleIO:

https://www.youtube.com/watch?v=IrMw7MEgADk&feature=youtu.be&t=857

Plus, if you're still not sure if you should use enums, you can hear a bunch of people yelling at each other in the comments of the first answer over here: https://stackoverflow.com/a/37839539/4036390


Old answer:

Just create the @IntDef class as a java class and access it via kotlin code.

Example:

  1. Create your type class:

    public class mType { @IntDef({typeImpl.type1, typeImpl.type2, typeImpl.type3}) @Retention(RetentionPolicy.SOURCE) public @interface typeImpl { int type1 = 0; int type2 = 1; int type3 = 2; } }

  2. Put this function in any Kotlin object:

    object MyObject{ fun accessType(@mType.typeImpl mType: Int) { ... } }

  3. then access it:

    fun somOtherFunc(){ MyObject.accessType(type1) }

**Notice: you don't have to put the access method inside an object.

Related