Reputation: 3245
Regarding many references in the network, I've found that using enum in android affects the performance badly. So for simpler int
or String
enums, they recommend using an annotation library @TypeDef
. But what if I have an enum like this?
enum class Heroes(
val heroName: String,
val heroLevel: Int,
val healthPoints: Int,
val xpMultipleMax: Double
) {
GLAZIER("Glazier", 1, 25, 1.2),
ONYX("Onyx", 2, 35, 1.3),
PARDUS("Pardus", 3, 50, 1.5),
EAGLE_EYE("Eagle eye", 4, 70, 1.7),
TORNADO("Tornado", 5, 100, 2.0)
}
Is it possible to apply the @TypeDef
here? And I think in this case even R8
and Proguard
can't help because as I know they just help to convert the enum to int
. But how they will convert it to int if I have multiple parameters for each enum?
P.S. I've created an enum, with a single integer value. Proguard is on, but after decompiling, I see, that it still uses enum under the hood.
enum class Heroes(
val heroLevel: Int,
) {
GLAZIER(1),
ONYX(3),
}
That's the enum. Now have a look at the decompiled class.
public enum Heroes {
GLAZIER,
ONYX;
private final int heroLevel;
public final int getHeroLevel() {
return this.heroLevel;
}
private Heroes(int heroLevel) {
this.heroLevel = heroLevel;
}
}
P.P.S Now folks at Google say its okay to use enums - Source
Upvotes: 0
Views: 418
Reputation: 6277
You can now use Enums in Android. It doesn't affect that much on performance in ART. It was discussed in the Google I/O You can refer the here in Video Google IO SpeedLink to Enum topic
If you want an alternate for enum in Kotlin, of course, you can always use Sealed classes.
This is how it looks in sealed class
//Enum version
enum class Heroes(
val heroName: String,
val heroLevel: Int,
val healthPoints: Int,
val xpMultipleMax: Double
) {
GLAZIER("Glazier", 1, 25, 1.2),
ONYX("Onyx", 2, 35, 1.3),
PARDUS("Pardus", 3, 50, 1.5),
EAGLE_EYE("Eagle eye", 4, 70, 1.7),
TORNADO("Tornado", 5, 100, 2.0)
}
//sealed class verison
sealed class Heroes(
val heroName: String,
val heroLevel: Int,
val healthPoints: Int,
val xpMultipleMax: Double
) {
class GLAZIER() : Heroes("Glazier", 1, 25, 1.2)
class ONYX() : Heroes("Onyx", 2, 35, 1.3)
class PARDUS() : Heroes("Pardus", 3, 50, 1.5)
class EAGLE_EYE() : Heroes("Eagle eye", 4, 70, 1.7)
class TORNADO() : Heroes("Tornado", 5, 100, 2.0) //use 'object' instead of 'class' if you want single instance.
}
Upvotes: 2