'Kotlin cannot make out that I've already checked whether the item is in the collection

val map = mapOf(
    'a' to 1,
    'b' to 2,
    'c' to 3
)

val c = 'a'
if (c in map) {
    println(map[c] + 1)
}

In the simple code stub, Kotlin compiler does not allow me to perform the operation in println. It yells to me with the following warning:

Operator call corresponds to a dot-qualified call 'map[c].plus(1)' which is not allowed on a nullable receiver 'map[c]'.

It drives me mad, I don't want to put !! to silence it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source