Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

499
Views
Does Kotlin allow you to assign custom value to enum?

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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

Also, you cannot override valueOf.

over 4 years ago · Santiago Trujillo Report

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())
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!