In Java we are told to strictly avoid using enums on Android because they take up twice the memory.
Does this apply to enum class
in Kotlin aswell? Will a Kotlin enum
be compiled into a Java enum
?
Enum values will take more memory compared to an int constant. Adding a single enum will increase the size of the final DEX file approximately 13x when to an integer constant. This is because each value in an enum class is treated as an object, and each value will take some heap memory to reference the object.
When ENUM type has a long list of values. ENUM types should not be used if you cannot limit a set of possible values to a few elements.
Casting from int to an enum is extremely cheap... it'll be faster than a dictionary lookup. Basically it's a no-op, just copying the bits into a location with a different notional type. Parsing a string into an enum value will be somewhat slower.
Enum in java is a data type that contains fixed set of constants. When we required predefined set of values which represents some kind of data, we use ENUM. We always use Enums when a variable can only take one out of a small set of possible values.
It would appear so, yes.
I created this in Kotlin:
enum class Thingies { Red, Green, Blue }
And decompiled it with javap -v
, and here is the header:
public final class Thingies extends java.lang.Enum<Thingies> minor version: 0 major version: 52 flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM
Bottom line: they are identical, so you probably have to treat them the same way.
They are exactly the same thing, a Kotlin Enum is a Java JVM Enum.
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