在 Scala 中定义 ChainedMap

发布于 2024-10-11 04:48:21 字数 991 浏览 1 评论 0原文

我试图在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福%小乖 2024-10-18 04:48:21

嗯,扩展 Scala 集合是很棘手的。有此参考,以及一些博客和堆栈溢出问题。但是,您不需要这样做,因为它已经受到支持。

scala> val parentMap = Map("x" -> 1, "y" -> 2)             
parentMap: scala.collection.immutable.Map[java.lang.String,Int] = Map((x,1), (y,2))

scala> val childMap = Map("a" -> 42) withDefault parentMap
childMap: scala.collection.immutable.Map[java.lang.String,Int] = Map((a,42))

scala> childMap("x")
res5: Int = 1

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.

scala> val parentMap = Map("x" -> 1, "y" -> 2)             
parentMap: scala.collection.immutable.Map[java.lang.String,Int] = Map((x,1), (y,2))

scala> val childMap = Map("a" -> 42) withDefault parentMap
childMap: scala.collection.immutable.Map[java.lang.String,Int] = Map((a,42))

scala> childMap("x")
res5: Int = 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文