在 Scala 中定义 ChainedMap
我试图在 http:// 之后定义一个“链式地图” steve-yegge.blogspot.com/2008/10/universal-design-pattern.html。我在定义伴随对象 apply
方法时遇到了问题。这是我想出的:
import scala.collection.generic.ImmutableMapFactory
import scala.collection.immutable.HashMap
class ChainedMap[A, B](private val superMap: ChainedMap[A, B])
extends HashMap[A, B] {
override def get(key: A): Option[B] = {
if (contains(key)) {
get(key)
} else if (superMap != null) {
superMap.get(key)
} else {
None
}
}
}
object ChainedMap extends ImmutableMapFactory[ChainedMap] {
override def apply[A, B](superMap: ChainedMap[A, B],
elems: (A, B)*): ChainedMap[A, B] = {
// What goes here?
}
}
这是我将如何使用它:
val parentMap = ChainedMap(null, "x" -> 1, "y" -> 2)
val childMap = ChainedMap(parentMap, "a" -> 42)
I am trying to define a "chained map" after http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html. I have run into a problem defining the companion object apply
method. Here is what I have come up with:
import scala.collection.generic.ImmutableMapFactory
import scala.collection.immutable.HashMap
class ChainedMap[A, B](private val superMap: ChainedMap[A, B])
extends HashMap[A, B] {
override def get(key: A): Option[B] = {
if (contains(key)) {
get(key)
} else if (superMap != null) {
superMap.get(key)
} else {
None
}
}
}
object ChainedMap extends ImmutableMapFactory[ChainedMap] {
override def apply[A, B](superMap: ChainedMap[A, B],
elems: (A, B)*): ChainedMap[A, B] = {
// What goes here?
}
}
Here is how I will use it:
val parentMap = ChainedMap(null, "x" -> 1, "y" -> 2)
val childMap = ChainedMap(parentMap, "a" -> 42)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,扩展 Scala 集合是很棘手的。有此参考,以及一些博客和堆栈溢出问题。但是,您不需要这样做,因为它已经受到支持。
Well, extending Scala collections is tricky. There's this reference, plus some blogs and Stack Overflow questions. However, you don't need to do it, because it is already supported.