Reverse instance of enum directly without class in Kotlin

In Kotlin, I cannot directly reference enumeration instances when E is in the same file as the code in which I use its instances:

enum class E {
    A, B
}

What I want to do:

val e = A    

What can I do:

val e = E.A

Is it possible?

+4
source share
1 answer

Yes it is possible!

In Kotlin, enum instances can be imported, like most other things, so if enum class E is in the default package, you can simply add import E.*to the top of the source file that you would like to use its instances directly. For instance:

import E.*
val a = A // now translates to E.A

Each instance can also be imported separately, and not just import everything into an enumeration:

import E.A
import E.B
//etc...

This also works, even if the enumeration is declared in the same file:

import E.*
enum class E{A,B}
val a = A
+5
source

Source: https://habr.com/ru/post/1682584/


All Articles