Issue
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!!
Solution
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")
Answered By - Karsten Gabriel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.