我想要一个尝试覆盖现有键的值的 Map。我试过了:
trait Unoverwriteable[A, B] extends scala.collection.Map[A, B] {
case class KeyAlreadyExistsException(e: String) extends Exception(e)
abstract override def + [B1 >: B] (kv: (A, B1)): Unoverwriteable[A, B1] = {
if (this contains(kv _1)) throw new KeyAlreadyExistsException(
"key already exists in WritableOnce map: %s".format((kv _1) toString)
)
super.+(kv)
}
abstract override def get(key: A): Option[B] = super.get(key)
abstract override def iterator: Iterator[(A, B)] = super.iterator
abstract override def -(key: A): Unoverwriteable[A, B] = super.-(key)
}
并得到:
<console>:11: error: type mismatch;
found : scala.collection.Map[A,B1]
required: Unoverwirteable[A,B1]
super.+(kv)
^
<console>:16: error: type mismatch;
found : scala.collection.Map[A,B]
required: Unoverwirteable[A,B]
abstract override def -(key: A): Unoverwirteable[A, B] = super.-(key)
^
我对 Scala 很陌生,无法找到克服这个问题的方法。有什么帮助吗?:)
编辑:我正在使用 Scala 2.8.0.Beta1-prerelease (这给 scala.collection 带来了一些变化)