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

如何实现任意key均返回固定值的Map并传入指定函数?

解决方案

在Scala中,你可以通过Map自带的withDefaultValue方法快速构造满足需求的参数,代码示例如下:

// 传入不可变Map,直接调用`map(key)`时所有key都返回"bar"
some(foo = Map.empty[SomeObject, String].withDefaultValue("bar"))

注意事项

  • 上述写法仅对apply方法(即直接用map(key)的方式取值)生效,如果调用方使用get方法查询,不存在的key仍会返回None
  • 如果需要覆盖所有查询行为,包括get、getOrElse等方法都返回对应预期结果,可以自定义Map实现类,示例如下:
val allReturnBarMap = new Map[SomeObject, String] {
  // 重写get方法,任意key都返回Some("bar")
  override def get(key: SomeObject): Option[String] = Some("bar")
  // 其余抽象方法按需实现即可,不涉及查询的方法不影响需求
  override def iterator: Iterator[(SomeObject, String)] = Iterator.empty
  override def removed(key: SomeObject): Map[SomeObject, String] = this
  override def updated[V1 >: String](key: SomeObject, value: V1): Map[SomeObject, V1] = this
}
// 传入自定义Map即可
some(foo = allReturnBarMap)
  • 如果你需要传入可变的Map实例,只需把上述的Map替换为scala.collection.mutable.Map,逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:36:03