【问题标题】:Increment element in mutable map in KotlinKotlin可变映射中的增量元素
【发布时间】:2021-03-11 06:20:18
【问题描述】:

我从 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 在 += 运算符上给我一个错误,抱怨“预期变量”,这对我来说是不透明的。为什么我不能这样做?我尝试了很多变化,但没有一个有效。如果我不使用 !! 运算符并从上下文菜单中选择 Add non-null asserted (!!) call,IntelliJ 甚至会提供生成相同的代码。

【问题讨论】:

  • 这能回答你的问题吗? Increase value in mutable map
  • 它没有。它只是提供了一些 hacky 解决方法,而没有解释为什么这么简单的东西不起作用。

标签: dictionary kotlin mutable mutablemap


【解决方案1】:

由于 operator fun get() 如果密钥不存在则返回 null,因此您可以使用 null 安全性而不是 if 检查:

val toPut = map[index]?.plus(3) ?: 0
map[index] = toPut

不能使用+ 的原因是因为operator fun Int.plus() 仅适用于非空Int 类型。虽然这看起来并没有那么糟糕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多