为什么我会收到错误:科特林中的变量期望



我正在尝试编写一个函数来查找 kotlin 中的多数元素,但是当我编译代码时,我在下一行收到变量预期错误

                   map[key]?.let{ value->

下面是我尝试运行的功能。我是 Kotlin 的新手,不确定为什么会出现此错误。

fun majorityElement(nums: IntArray): Int {
        HashMap<Int,Int>().let{ map ->
                nums.forEach{ key->        
                   map[key]?.let{ value->
                        map[key]=value+1
                    }?:map[key]=1
                }
                map.forEach{entry->
                    if(entry.value>nums.size/2){
                        return entry.key
                    }
                }
        }
        return -1
    }

基本上问题出在这一部分:

map[key]?.let { ... } ?: map[key] = 1

在这里,表达式的解析方式不是您所期望的。 map[key]?.let { ... } ?: map[key] 成为赋值运算符的 l 值,1 成为 r 值。

赋值的 l 值必须是您可以为其赋值的东西,即变量、属性、索引器,如 map[key] = ,但这里它是一个复杂的表达式 map[key]?.let { ... } ?: map[key] .

如果只想在 map[key] 为 null 时执行赋值,则可以将该语句包装在run函数中:

map[key]?.let { ... } ?: run { map[key] = 1 }

也许通过以下方式重写此块会更清楚:

// get value associated with key or 0 if there is none.
map[key] = map.getOrElse(key, { 0 }) + 1

从更高的角度来看,您似乎需要计算整数数组中数字的出现次数。对于这种情况,可以使用具有groupingByeachCount函数的更高级的方法:

val map = nums.asList().groupingBy { it }.eachCount()
// then find the majority in this map

最新更新