I am new to Kotlin and tried to google it, but I don't get it.
Example here: https://try.kotlinlang.org/#/UserProjects/q4c23aofcl7lb155oc307cnc5i/sgjm2olo277atiubhu2nn0ikb8
Code:
fun main(args: Array<String>) {
val foo = mutableMapOf('A' to 0, 'C' to 0, 'G' to 0, 'T' to 0)
foo['A'] = foo['A'] + 1
println("$foo['A']")
}
I don't get it; why does the indexing operator return the nullable type? The map in the example is defined as Map<Char, Int>
, not Map<Char, Int?>
.
I can override it via non-null assertion, so this works:
foo['A'] = foo['A']!!.plus(1)
Is there a cleaner way?
You can use the index operator with arbitrary chars, even those that are not part of the map, as in not an existing key. There are two obvious solutions to this, either throw an exception or return null
. As you can see in the documentation, the standard library returns null
in the operator fun get
, which the index operator translates to:
/** * Returns the value corresponding to the given [key], or `null` if such a key is not present in the map. */ public operator fun get(key: K): V?
The alternative is getValue
which is described like this:
Returns the value for the given [key] or throws an exception if there is no such key in the map.
Used like this: val v: Int = foo.getValue('A')