This is throwing the error: Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Color.red
enum class Color(val value: String = "") {
RED("red"),
YELLOW("yellow"),
BLUE("blue")
}
fun main() {
print(Color.valueOf("red"))
}
The above will only work if I change the print statement to:
print(Color.valueOf("RED"))
Is it possible to use a custom string to assign to an enum value using the valueOf?
As you discovered, the enum valueOf() method looks up by the name of the enum constant, not by any properties you add.
But you can easily add your own lookup method, using whatever criteria you want:
enum class Color(val hue: String) {
RED("red"),
YELLOW("yellow"),
BLUE("blue");
companion object {
fun forHue(hue: String) = values().find{ it.hue == hue }
}
}
A call to Color.forHue("red") returns the Color.RED instance as expected.
(This is probably the simplest approach, but not the most efficient; see answers such as this.)
No, but you can write your own method and get the value by iteration, when, or map.
Also, you cannot override valueOf.
You can implement your own valueOfwhich works case-insensitively:
enum class Color(val value: String = "") {
RED("red"),
YELLOW("yellow"),
BLUE("blue");
companion object {
//TODO: gimme a better name
fun customValueOf(val: String) = valueOf(val.toUpperCase())
}
}