提问人:Urban Vagabond 提问时间:11/29/2020 更新时间:11/29/2020 访问量:428
在 Kotlin 的可变映射中增量元素
Increment element in mutable map in Kotlin
问:
我将从 Scala 来到 Kotlin 1.3。我正在尝试做一些非常简单的事情:
class Foo {
fun bar() {
val map = mutableMapOf<String, Int>()
val index = "foo"
if (index !in map)
map[index] = 0
else
map[index]!! += 1
}
}
但是,IntelliJ 2020 在运算符上给了我一个错误,抱怨“预期变量”,这对我来说是不透明的。为什么我不能这样做?我尝试了很多变化,但没有一个有效。IntelliJ 甚至提供如果我省略运算符并从上下文菜单中进行选择,则可以生成相同的代码。+=
!!
Add non-null asserted (!!) call
答:
0赞
Animesh Sahu
11/29/2020
#1
由于如果密钥不存在,则返回 null,因此可以使用 null 安全性而不是 if 检查:operator fun get()
val toPut = map[index]?.plus(3) ?: 0
map[index] = toPut
不能使用的原因是因为它仅适用于非 null 类型。虽然这看起来还不错。+
operator fun Int.plus()
Int
评论