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?
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 .
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.
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.
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.
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
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