如何在 Scala 中使用默认操作实现 Map [英] How to implement Map with default operation in Scala
本文介绍了如何在 Scala 中使用默认操作实现 Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class DefaultListMap[A, B <: List[B]] extends HashMap[A, B] {
override def default(key: A) = List[B]()
}
我不想创建地图 A ->列表[B]
.就我而言,它是 Long ->List[String]
但是当我从没有值的地图中获取键时,我想创建空的 List
而不是 Exception
被抛出.我尝试了不同的组合,但我不知道如何让上面的代码通过编译器.
I wan't to create map A -> List[B]
. In my case it is Long -> List[String]
but when I get key from map that doesn't have value I would like to create empty List
instead of Exception
being thrown. I tried different combinations but I don't know how to make code above pass the compiler.
提前致谢.
推荐答案
为什么不使用 withDefaultValue(value)?
Why not to use withDefaultValue(value)?
scala> val m = Map[Int, List[String]]().withDefaultValue(List())
m: scala.collection.immutable.Map[Int,List[String]] = Map()
scala> m(123)
res1: List[String] = List()
这篇关于如何在 Scala 中使用默认操作实现 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文