Home > Mobile >  Map.computeIfAbsent requires not null result in Kotlin
Map.computeIfAbsent requires not null result in Kotlin

Time:11-23

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.

  • Related