7

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?

s-hunter
  • 24,172
  • 16
  • 88
  • 130

4 Answers4

8

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

gidds
  • 16,558
  • 2
  • 19
  • 26
1

No, but you can write your own method and get the value by iteration, when, or map.

Also, you cannot override valueOf.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

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())
    }
}
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
0
enum class Colour(var value: String = "") {
    RED("red"),
    YELLOW("yellow"),
    BLUE("blue");
}

fun main() {
    Colour.RED.value = "dark red"
    println(Colour.RED.value)
}
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Jul 13 '23 at 03:40