You are currently viewing I think the (JVM?) implementation of Map.getOrElse is confusing.

I think the (JVM?) implementation of Map.getOrElse is confusing.

The implementation looks like this in Map.kt:

@kotlin.internal.InlineOnly public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue() 

Which seems trivial at first glance, but is incorrect if V is nullable, which is allowed in Map. So if you use getOrElse on your map that can have null values, you’re very likely making a mistake.

Below it, in the same file, I see:

internal inline fun <K, V> Map<K, V>.getOrElseNullable(key: K, defaultValue: () -> V): V { val value = get(key) if (value == null && !containsKey(key)) { return defaultValue() } else { @Suppress("UNCHECKED_CAST") return value as V } } 

Which is more correct, IMO. But it’s internal. Why doesn’t Kotlin use the safer version by default? And why doesn’t it at least expose the safer version as an option?

submitted by /u/ragnese
[link] [comments]