Kotlin中Max函数工作原理及MutableMap使用异常排查
Kotlin MutableMap中max()函数异常的原因及修复
核心问题
scores.values.max() 返回的是 Int?(可空整数类型),而后续代码中 score == highScore 里的 score 是 Int(非空类型),类型不匹配导致逻辑异常或编译警告。
具体原因
Kotlin里空集合调用max()会返回null——因为没有元素可取最大值。你的代码未处理highScore为null的情况,会引发两种问题:
- 若
scores是空Map,highScore为null,score == null永远不成立,返回的 winners 集合为空,不符合空集合的预期处理逻辑; - 非空场景下,虽然编译不会报错,但可空类型和非空类型直接比较属于不严谨写法,容易埋下隐患。
修复方案
方案1:手动处理空值+保留原循环逻辑
fun getWinners(): MutableSet<T> { val winners: MutableSet<T> = mutableSetOf() val highScore = scores.values.max() ?: return winners // 空集合直接返回空结果 for ((t, score) in scores) { if (score == highScore) winners.add(t) } return winners }
方案2:用Kotlin内置函数简化代码
fun getWinners(): MutableSet<T> { val highScore = scores.values.max() ?: return mutableSetOf() return scores.filterValues { it == highScore }.keys.toMutableSet() }
额外注意
你的代码应该属于泛型类,需要在类声明时指定泛型参数T,否则会编译报错,完整示例如下:
class ScoreManager<T> { val scores: MutableMap<T, Int> = mutableMapOf() fun addScore(t: T, score: Int = 0) { if (score >= 0) scores[t] = score // 用[]赋值比put更符合Kotlin风格 } fun getWinners(): MutableSet<T> { val highScore = scores.values.max() ?: return mutableSetOf() return scores.filterValues { it == highScore }.keys.toMutableSet() } }
内容的提问来源于stack exchange,提问作者offpeak
相关产品推荐
相关产品推荐

