Map.computeIfAbsent 在 Kotlin 中要求非空结果

Map.computeIfAbsent requires not null result in Kotlin

代码片段

val map = mutableMapOf<String, String>()
map.computeIfAbsent(key) { calcValue(it) }

带有 calcValue 签名:

fun calcValue(key: String): String?

编译错误:

Type mismatch: inferred type is String? but String was expected

但是mappingFunction到returnnullMap.computeIfAbsent.

是可以接受的

这是一个错误吗?还是我做错了什么?

这显然是 kotlin 团队为了简化使用而明确不允许的。请参阅此处的解释:https://youtrack.jetbrains.com/issue/KT-10982#focus=streamItem-27-2187715.0-0

因此要么使用 compute,要么使用可空类型作为映射中的值。