I'm trying to migrate some code from Java to Kotli...
# announcements
d
I'm trying to migrate some code from Java to Kotlin, it has an annotation where I used constants inside the annotation (in Java):
Copy code
@IntDef(
            flag = false,
            value = {
                    AspectRatioMode.AUTO,
                    AspectRatioMode.BY_WIDTH,
                    AspectRatioMode.BY_HEIGHT,
            }
    )
    public @interface AspectRatioMode {
        int AUTO = 0;
        int BY_WIDTH = 1;
        int BY_HEIGHT = 2;
    }
@IntDef
is an Android annotation allowing to define an annotation for Integer constants on Integers:
Copy code
@AspectRatioMode
int myMode = AspectRatioMode.AUTO; // can only be one of AUTO / BY_WIDTH / BY_HEIGHT
While in kotlin the conversion would be:
Copy code
@IntDef(flag = false, value =[
        AspectRatioMode.AUTO,
        AspectRatioMode.BY_WIDTH,
        AspectRatioMode.BY_HEIGHT
    ])
    annotation class AspectRatioMode {
        companion object {
            val AUTO = 0
            val BY_WIDTH = 1
            val BY_HEIGHT = 2
        }
    }
but I get an error on `companion object`: "Members are not allowed in annotation class" I can move those constants out:
Copy code
object AspectRatioModeConst {
        const val AUTO = 0
        const val BY_WIDTH = 1
        const val BY_HEIGHT = 2
    }

    @IntDef(flag = false, value = [
        AspectRatioModeConst.AUTO,
        AspectRatioModeConst.BY_WIDTH,
        AspectRatioModeConst.BY_HEIGHT
    ])
    annotation class AspectRatioMode
but that is a lot uglier then Java where I could more cleanly use the annotation directly for constants.
Copy code
@AspectRatioMode
val myGoodMode : Int = AspectRatioMode.AUTO; // I want this
val myBadMode : Int = AspectRatioModeConst.AUTO; // not this
Is there any other way I can obtain the same result of Java with Kotlin?
c
I'm wondering if it would be infeasible to simply migrate to enums instead. See also: https://www.reddit.com/r/androiddev/comments/7so7ne/you_should_strictly_avoid_using_enums_on_android/dt6aqki/
d
@cbruegg According to this article enum are bad for performance in Android: https://android.jlelse.eu/android-performance-avoid-using-enum-on-android-326be0794dc3 I'm not sure if this is still the case, but this was the main reason I went for Int in that code
👎 2
c
It's a micro-optimization that may make sense for the Android framework, but for most applications, it probably won't make a difference. Generally, before making such optimizations, I'd advise to benchmark first.
One more thing, the Reddit comment I've linked to is by Jake Wharton, who actually now works in the Android Framework Team at Google.
d
Yeah I know Jake 🙂 And still have to read the link
I just trusted them about that
I guess I shouldn't have
Also you can keep your annotation in Java for now to avoid API changes and wait 1.3, looks exactly the same for Kotlin and Java