In Kotlin, I'm unable to reference the instances of an enum directly when E is in the same file as the code where I use its instances:
enum class E {
A, B
}
What I want to do:
val e = A
What I can do:
val e = E.A
Is this possible?
You need to use val if you want it to be a property: enum class TimeStamps(val value: Long, val text: String) { ... }
Implementing Interfaces In enums In Kotlin, you can also have enums implement interfaces. In such cases, each data value of enum would need to provide an implementation of all the abstract members of the interface. While calling these interface methods, we can directly use the enum value and call the method.
In Kotlin, enum instances can be imported like most other things, so assuming enum class E is in the default package, you can just add import E.*
to the top of the source file that would like to use its instances directly. For example:
import E.*
val a = A // now translates to E.A
Each instance can also be imported individually, instead of just importing everything in the enum:
import E.A
import E.B
//etc...
This also works even if the enum is declared in the same file:
import E.*
enum class E{A,B}
val a = A
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