如何在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
。我尝试了不同的组合,但我不知道如何使上面的代码通过编译器。
提前致谢。
class DefaultListMap[A, B <: List[B]] extends HashMap[A, B] {
override def default(key: A) = List[B]()
}
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.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不使用 withDefaultValue(value) ?
Why not to use withDefaultValue(value)?
您可以始终使用
get
,而不是使用apply
访问地图,它返回Option[V]
,然后返回getOrElse
code>:scalaz函数式编程库的一个重要功能是一元运算符
~
,它的意思是“或零”,只要值类型定义了一个“零”(List
就是这样,零当然是Nil
)。所以代码就变成了:这是双重有用的,因为相同的语法适用于(例如)您的值为
Int
、Double
等(任何有>零
类型类)。关于使用 Map.withDefault 的 Scala 邮件列表存在很多争论,因为它在 isDefinedAt 方法等方面的表现如何。由于这个原因,我倾向于避开它。
Rather than using
apply
to access the map, you could always useget
, which returnsOption[V]
and thengetOrElse
:One great feature of the scalaz functional-programming library is the unary operator
~
, which means "or zero",as long as the value type has a "zero" defined (whichList
does, the zero beingNil
of course). So the code then becomes:This is doubly useful because the same syntax works where (for example) your values are
Int
,Double
etc (anything for which there is aZero
typeclass).There has been a great deal of debate on the scala mailing list about using
Map.withDefault
because of how this then behaves as regards theisDefinedAt
method, among others. I tend to steer clear of it for this reason.Map
上有一个方法withDefaultValue
:There's a method
withDefaultValue
onMap
:当地图已经有方法时,为什么还要操作地图呢?
Why do you want to manipulate a map when it has already a method for this?
也可以使用withDefault。
示例:
希望这会有所帮助。
withDefault can also be used.
Example:
Hope this helps.