https://kotlinlang.org logo
Title
s

snowe

04/09/2019, 8:25 PM
called like this
incomeTypes.forEach {
            val incomeType = IncomeType.valueOf(it, IncomeType.UNKNOWN)
p

Pavlo Liapota

04/09/2019, 8:57 PM
Maybe this would be useful https://stackoverflow.com/a/51663849 So you can write
enumConstants.firstOrNull { it.name == name } ?: default
s

snowe

04/09/2019, 8:58 PM
Oops! I forgot to update this after finding a good solution. I think I'm actually going to recommend
inline fun <reified T: Enum<T>> String.enumWithDefault(defaultValue: T) : T {
    return try{
        enumValues<T>().first {it.name == this }
    } catch (e: NoSuchElementException) {
        defaultValue
    }
}
or
inline fun <reified T : Enum<T>> enumValueOf(name: String, defaultValue: T): T {
    return try {
        enumValues<T>().first { it.name == name }
    } catch (e: NoSuchElementException) {
        defaultValue
    }
}
to the dev.
I like the first one more as it is a bit easier to read
sorry haha. but it looks like that link is in the same vein as what I'm doing.
b

Burkhard

04/09/2019, 10:28 PM
if you care about performance you should probably use
firstOrNull { it.name == name } ?: default
. Creating Exceptions is quite expensive, because of the generated stack trace.
3
s

snowe

04/10/2019, 3:51 PM
Yeah I know. We don't really care about performance. 😅 it's the mortgage world
b

Burkhard

04/10/2019, 3:55 PM
Still, small things like this add up, and I’d argue that the version without excpetions looks even better. And while you shouldn’t prematurely optimize code it’s also bad to write code, that is just slow, even though the faster alternative has no donesides (development time or complexity)
s

snowe

04/10/2019, 4:08 PM
I'll recommend your version then. I think it is more readable.