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.
Since the
operator fun get()returns null if the key doesn't exist, you can use the null safety instead of the if check:The reason you cannot use
+is becauseoperator fun Int.plus()is only applicable to non-nullInttypes. Though this doesn't looks that bad.