You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala自定义类型Map判断键存在返回False的问题求助

问题原因及解决方案

核心问题

Scala中使用自定义类型作为Map的键时,Map依赖equals()和hashCode()方法判断键的相等性。你的configKey类仅重写了toString(),未重写这两个方法,导致默认使用引用相等性判断——即使两个configKey实例的repRole值相同,只要是不同对象,就会被视为不同的键。

另外,最后一段代码存在拼写错误:configKeys.agentRole = AGENTROLE中的agentRole并非configKey类的成员变量,正确应为repRole,否则新创建的configKeys对象的repRole是空字符串,自然无法匹配已存入Map的键。

修正步骤

1. 重写configKey的equals()和hashCode()方法

修改configKey类,确保基于repRole的值判断相等性:

class configKey(var repRole: String = "") extends Serializable {
  override def toString(): String = repRole

  override def equals(obj: Any): Boolean = obj match {
    case other: configKey => other.repRole == this.repRole
    case _ => false
  }

  override def hashCode(): Int = repRole.hashCode()
}

2. 修正拼写错误

将最后一段代码中的configKeys.agentRole改为configKeys.repRole:

var AGENTROLE: String = "CUST EXE"
var configKeys: configKey = new configKey()
var configKeyDef: configKey = new configKey()
configKeys.repRole = AGENTROLE; // 修正此处的拼写错误
configKeyDef.repRole = "Default";

if(tempConfigMap.contains(configKeys))
  println("True")
else
  println("False")

原理说明

  • equals():定义了两个configKey对象相等的逻辑——当且仅当它们的repRole值相同。
  • hashCode():基于repRole的哈希值生成,确保相等的对象必有相同的哈希码,这是Map正确工作的必要条件(哈希表依赖哈希码快速定位桶位置,再通过equals确认相等)。

内容的提问来源于stack exchange,提问作者Tech Fukrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:25:57