https://kotlinlang.org logo
#announcements
Title
# announcements
m

Mani

11/06/2019, 10:06 AM
Copy code
val pickableState = try {
            PickableState.valueOf(state)
        } catch (ex: Exception){
            null
        }
is there a better way to check if a string is present in ENUM?
j

Jonathan Mew

11/06/2019, 10:23 AM
I'd do:
val pickableState: PickableState? = PickableState.values().find{it.name == state}
m

Mani

11/06/2019, 6:48 PM
.values will give you all values, right, is there a better way?
j

Jonathan Mew

11/07/2019, 7:41 AM
A better way to achieve what? Could you rephrase your question?
m

Matteo Mirk

11/08/2019, 3:32 PM
you could incapsulate your recurring logic in a top-level generic function:
Copy code
inline fun <reified E : Enum<E>> enumIsPresent(name: String): Boolean {
    return try {
        enumValueOf<E>(name)
        true
    } catch (e: Exception) {
        false
    }
}
2 Views