called like this ``` incomeTypes.forEach {...
# codereview
s
called like this
Copy code
incomeTypes.forEach {
            val incomeType = IncomeType.valueOf(it, IncomeType.UNKNOWN)
p
Maybe this would be useful https://stackoverflow.com/a/51663849 So you can write
Copy code
enumConstants.firstOrNull { it.name == name } ?: default
s
Oops! I forgot to update this after finding a good solution. I think I'm actually going to recommend
Copy code
inline fun <reified T: Enum<T>> String.enumWithDefault(defaultValue: T) : T {
    return try{
        enumValues<T>().first {it.name == this }
    } catch (e: NoSuchElementException) {
        defaultValue
    }
}
or
Copy code
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
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
Yeah I know. We don't really care about performance. 😅 it's the mortgage world
b
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
I'll recommend your version then. I think it is more readable.