Why is the result of the computeIfAbsent lambda non-nullable?

I’m not sure if this is a bug or a lack of understanding on my part, but I was surprised with the following null behavior:

val testMap = mutableMapOf<String, String>()
testMap.computeIfPresent("test") { key, value ->
    null // this works
}
testMap.computeIfAbsent("test") { key ->
    null // this doesn't: "Null can not be a value of a non-null type String"
}

Java docs for computeIfAbsent specifically state “[i]f the function returns null no mapping is recorded”, so returning null in that lambda should be valid behavior. Does Kotlin have a different implementation of computeIfAbsent or is this perhaps an issue with how the lambda type is interpreted?

It seems to be done on purpose by Kotlin team:

You can find some reasoning for such decision here:
https://youtrack.jetbrains.com/issue/KT-10982#focus=streamItem-27-2187715.0-0

2 Likes