Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

506
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda