Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference enum instance directly without class in Kotlin

Tags:

enums

kotlin

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?

like image 513
Julian A. Avatar asked Jul 30 '17 03:07

Julian A.


People also ask

How do you access enum in Kotlin?

You need to use val if you want it to be a property: enum class TimeStamps(val value: Long, val text: String) { ... }

Can enum implement an interface in Kotlin?

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.


Video Answer


1 Answers

Yes, this is possible!

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
like image 138
Ryan Hilbert Avatar answered Oct 22 '22 16:10

Ryan Hilbert