Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

467
Visualizações
How to select correct enum value from a kotlin function

i am expecting some string value and i need to find, if i have corresponding enum value defined.

my enum value is

enum class Status {
    Created, Updated
}

and what i want to achieve in this function is to check if any of these enum values matching, ignore the case

private fun getStatus(
        value: String
    ): Status {
        ....
    }

if nothing matched then i want to throw an error.

thank you so much for your help in advance!!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Note: in this answer, I missed the requirement that the function should be case-insensitive. Those built-in functions only find exact matches.


Original answer:

There is a built-in valueOf() function that you can use which does exactly that:

val status = Status.valueOf("Created")

If you're in a generic context and cannot use the enum class name directly, you can also use enumValueOf():

val status = enumValueOf<Status>("Created")

Here is the doc about this: https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants

over 4 years ago · Santiago Trujillo Relatório

0

The built-in functions for enums like Enum.valueOf or enumValueOf<Enum> are case-sensitive, but you can easily write your own case-insensitive versions:

inline fun <reified T : Enum<T>> enumValueOfIgnoreCase(key: String): T =
    enumValues<T>().find { it.name.equals(key, ignoreCase = true) }
        ?: throw IllegalArgumentException("no value for key $key")

Then you can write for instance the following to obtain the Status element Created:

val status = enumValueOfIgnoreCase<Status>("created")
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda