Code snippet
val map = mutableMapOf<String, String>()
map.computeIfAbsent(key) { calcValue(it) }
with calcValue
signature:
fun calcValue(key: String): String?
compiles with error:
Type mismatch: inferred type is String? but String was expected
But it is acceptable for mappingFunction
to return null
in Map.computeIfAbsent
.
Is this a bug? Or am I doing something wrong?
CodePudding user response:
This was apparently explicitely not allowed by the kotlin team to simplify the usage. See explanation here: https://youtrack.jetbrains.com/issue/KT-10982#focus=streamItem-27-2187715.0-0
So either use compute
or use a nullable type as value in the map.