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

Incrementing the mutable map value results in a nullable receiver error

提问人:Lyn 提问时间:6/6/2019 更新时间:6/6/2019 访问量:146

问:

我是 Kotlin 的新手,并试图用谷歌搜索它,但我不明白。

示例如下: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?>

我可以通过非空断言覆盖它,所以这有效:

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

有没有更清洁的方法?

字典 科特林 可变

评论


答:

1赞 s1m0nw1 6/6/2019 #1

您可以将索引运算符与任意字符一起使用,即使是那些不属于映射的字符,例如在非现有键中。对此有两个明显的解决方案,要么抛出异常,要么返回。正如您在文档中看到的,标准库返回 ,索引运算符将其转换为:nullnulloperator 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')

评论

0赞 Lyn 6/6/2019
啊,我现在明白了。谢谢!