1

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.

Urban Vagabond
  • 7,282
  • 3
  • 28
  • 31
  • 1
    Does this answer your question? [Increase value in mutable map](https://stackoverflow.com/questions/53826903/increase-value-in-mutable-map) – LeoColman Nov 28 '20 at 21:46
  • It doesn't. It just gives some hacky workarounds without explaining why something so simple doesn't work. – Urban Vagabond Nov 28 '20 at 22:10

1 Answers1

0

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.

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49