Increment element in mutable map in Kotlin

482 views Asked by At

I am coming to Kotlin 1.3 from Scala. I am trying to do something very simple:

class Foo {
    fun bar() {
        val map = mutableMapOf<String, Int>()
        val index = "foo"
        if (index !in map)
          map[index] = 0
        else
          map[index]!! += 1
    }
}

However, IntelliJ 2020 gives me an error on the += operator, complaining that "Variable expected", which is opaque to me. Why can't I do this? I have tried lots of variations but none works. IntelliJ even offers to generate the identical code if I leave off the !! operator and select Add non-null asserted (!!) call from the context menu.

1

There are 1 answers

0
Animesh Sahu On

Since the operator fun get() returns null if the key doesn't exist, you can use the null safety instead of the if check:

val toPut = map[index]?.plus(3) ?: 0
map[index] = toPut

The reason you cannot use + is because operator fun Int.plus() is only applicable to non-null Int types. Though this doesn't looks that bad.