Map.computeIfAbsent 要求 Kotlin 中结果不为空

Nol*_*uen 3 null dictionary kotlin

代码片段

val map = mutableMapOf<String, String>()
map.computeIfAbsent(key) { calcValue(it) }
Run Code Online (Sandbox Code Playgroud)

calcValue签名:

fun calcValue(key: String): String?
Run Code Online (Sandbox Code Playgroud)

编译时出现错误:

类型不匹配:推断类型是 String?但预期是字符串

mappingFunction但回国还是可以接受nullMap.computeIfAbsent

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

som*_*ing 5

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

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