Reputation: 15336
Is there a way to auto-cast or auto-convert strings to enums?
enum class Direction {
north, south, west, east
}
fun main() {
val d: Direction = "north" // <== Fails here
}
P.S.
I'm looking for short and clean way to use enums, like literal (algebraic) string type in TypeScript.
Or, alternatively, make the following code work, please not that north
is unqualified and conflicting.
enum class Direction {
north, south, west, east
}
enum class Compass {
north, south, west, east
}
fun main() {
val d: Direction = north // <== Fails here
val c: Compass = north // <== Fails here
}
Upvotes: 1
Views: 1598
Reputation: 21095
Migrating OP response from the question to an answer:
Currently it's not possible, there's KT-16768 issue, please vote if you would like to have this feature.
Upvotes: -1
Reputation: 9944
Your second example isn't currently possible, because you'd need two imports that would conflict with each other. Other answers have addressed the first example, which requires using something like valueOf
.
However, there is a proposal that would make the second example possible. It was recently included in the Kotlin features survey, and it's tracked under KT-16768 in the Kotlin issue tracker. The proposed new feature would let you use unqualified enum names without an import in situations where the expected type is known. In your example, even though the two enum values have the same name, the compiler would be able to tell which enum to use in each case because of the types that are specified in the variable declarations.
You can find out even more in the video webinar that was published on YouTube to accompany the survey.
Upvotes: 1
Reputation: 93581
Put import Direction.*
at the top of the file you want to do this in, even if it’s the same file you defined the enum in. Then you can use the enum values without qualifying them. No quotation marks needed. This won’t work for both of your enums at the same time if they have values with matching names, however.
Upvotes: 0
Reputation: 11486
It's not possible the way you want. The only thing closer is the static method valueOf
:
enum class Direction {
north, south, west, east
}
fun main() {
val d: Direction = Direction.valueOf("north")
println(d)
// Prints north
}
Upvotes: 3