作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 Scala 的新手,所以我开始用 Scala 重写我的旧代码。现在,我正在重写一个 Map,其中包含一些值和它们修改的“历史”(如添加、删除等):
import scala.collection.immutable._
class Storage[A,+B](private var oldValues: Map[A,B]) extends Map[A,B] {
private var addedValues = new HashMap[A,B]
private var modifiedValues = new HashMap[A,B]
private var deletedValues = new HashSet[A]
}
当我覆盖方法“+”时,我无法编译它:
override def +[B1 >: B](kv: (A,B1)) = {
deletedValues = deletedValues - kv._1
addedValues = addedValues + kv //type mismatch; found : (A, B1) required: (A, B)
modifiedValues = modifiedValues + kv //type mismatch; found : (A, B1) required: (A, B)
currentValues()
}
谁能告诉我在这种情况下我该怎么办?
最佳答案
问题是(值类型)B
的协方差。由于您使用的是可变状态,因此您可能应该使用可变 Map
特征,无论如何它在类型 B
中都不是协变的。如何扩展 HashMap
实现?以下编译,但我没有测试过,
import collection.mutable._
class Storage[A,B](private var oldValues: Map[A,B]) extends HashMap[A,B] {
private var addedValues: Map[A,B] = new HashMap[A,B]
private var modifiedValues: Map[A, B] = new HashMap[A,B]
private var deletedValues: Set[A] = new HashSet[A]
// Overriding this method will redefine the behavior of HashMap.put and HashMap.+=
override def addEntry(e: DefaultEntry[A, B]) {
super.addEntry(e)
// your extension code below
val kv = (e.key, e.value)
deletedValues -= kv._1
addedValues += kv
modifiedValues += kv
// currentValues() // not defined yet
}
}
storage += (key, value)
之类的调用将使用您修改后的 addEntry
方法。如果您还没有这样做,您可能需要熟悉从 the ScalaDoc 链接的 HashMap
的源代码。 .
关于Scala 逆变困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7218003/
COW 不是奶牛,是 Copy-On-Write 的缩写,这是一种是复制但也不完全是复制的技术。 一般来说复制就是创建出完全相同的两份,两份是独立的: 但是,有的时候复制这件事没多大必要
我是一名优秀的程序员,十分优秀!