递增可变映射值会导致可为空的接收器错误

时间:2019-06-06 09:41:35

标签: dictionary kotlin nullable mutable

我是Kotlin的新手,曾尝试用Google搜索它,但我不明白。

此处的示例: https://try.kotlinlang.org/#/UserProjects/q4c23aofcl7lb155oc307cnc5i/sgjm2olo277atiubhu2nn0ikb8

代码:

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']")    
}

我不明白。为什么索引运算符返回可为null的类型?示例中的地图定义为Map<Char, Int>,而不是Map<Char, Int?>

我可以通过非null断言来覆盖它,所以这可行:

foo['A'] = foo['A']!!.plus(1)

有没有更清洁的方法?

1 个答案:

答案 0 :(得分:1)

您可以将index运算符与任意字符一起使用,即使那些不属于映射的字符也可以与现有键一起使用。有两种明显的解决方案,要么抛出异常,要么返回null。如您在文档中所见,标准库在null中返回operator fun get,索引运算符将其转换为:

/**
 * 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?

替代方法是getValue,其描述如下:

  

返回给定[key]的值,或者如果映射中没有这样的键,则抛出异常。

像这样使用:val v: Int = foo.getValue('A')