Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize enum from associated value

Tags:

enums

kotlin

I would like to initialize enum by its associated value.

My enum:

enum class DirectionSwiped(raw: Int){
    LEFT(4),
    RIGHT(8);
}

I would like to initialize it as such:

val direction = DirectionSwiped(raw: 4)

But I get this error:

Enum type cannot be instantiated

Why is this happening? In Swift, this functionality works like this:

enum Direction: Int {
    case right = 2
}

let direction = Direction(rawValue: 2)

How can I make it work in Kotlin?

like image 931
Mickael Belhassen Avatar asked Dec 17 '18 19:12

Mickael Belhassen


People also ask

Can you give useful examples of enum associated values?

Let's see an example, enum Distance { // associate value case km(String) ... } Here, (String) is additional information attached to the value km . It represents that the value of km can only be a String .

What is associated value?

The association value of a stimulus is a measure of its meaningfulness. It is a strong predictor of how easy it is to learn new information about that stimulus, for example to learn to associate it with a second stimulus, or to recall or recognize it in a memory test.

Can associated values and raw values coexist in Swift enumeration?

The Problem with Associated Values We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values.

Can enum be initialized?

Enum constructors can never be invoked in the code — they are always called automatically when an enum is initialized. You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes.


1 Answers

Yes you can

enum class DirectionSwiped(val raw: Int){
    LEFT(4),
    RIGHT(8);
}

val left = DirectionSwiped.LEFT
val right = DirectionSwiped.RIGHT

val leftRaw = DirectionSwiped.LEFT.raw
val rightRaw = DirectionSwiped.LEFT.raw

val fromRaw = DirectionSwiped.values().firstOrNull { it.raw == 5 }

This would be the correct way to access the instances of the enum class

What you are trying to do is create a new instance outside the definition site, which is not possible for enum or sealed classes, that's why the error says the constructor is private

like image 175
Omar Mainegra Avatar answered Oct 14 '22 08:10

Omar Mainegra