Nolequen
Nolequen

Reputation: 4337

Map.computeIfAbsent requires not null result in Kotlin

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?

Upvotes: 3

Views: 3502

Answers (1)

somethingsomething
somethingsomething

Reputation: 2199

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.

Upvotes: 5

Related Questions