我正在尝试编写一个ForwardingMutableMap
特性,一个 la Guava's ForwardingMap
for Java。
这是我的拳头尝试的样子:
trait ForwardingMutableMap[K, V, +Self <: mutable.MapLike[K, V, Self] with mutable.Map[K, V]]
extends mutable.Map[K, V]
with mutable.MapLike[K, V, Self] { this: Self =>
protected val delegate: mutable.Map[K, V]
def get(key: K): Option[V] = delegate.get(key)
def iterator: Iterator[(K, V)] = delegate.iterator
def -=(key: K): this.type = {
delegate -= key
this
}
def +=(kv: (K, V)): this.type = {
delegate += kv
this
}
}
这会导致错误:
error: overriding method empty in trait MapLike of type => Self;
method empty in trait Map of type => scala.collection.mutable.Map[K,V] has incompatible type
trait ForwardingMutableMap[K, V, +Self <: mutable.MapLike[K, V, Self] with mutable.Map[K, V]]
第二次尝试:
trait ForwardingMutableMap[K, V, +Self <: mutable.MapLike[K, V, Self] with mutable.Map[K, V]]
extends mutable.Map[K, V]
with mutable.MapLike[K, V, Self] { this: Self =>
def empty: Self
protected val delegate: mutable.Map[K, V]
def get(key: K): Option[V] = delegate.get(key)
def iterator: Iterator[(K, V)] = delegate.iterator
def -=(key: K): this.type = {
delegate -= key
this
}
def +=(kv: (K, V)): this.type = {
delegate += kv
this
}
}
错误:
error: overriding method empty in trait ForwardingMutableMap of type => ForwardingMutableMap.this.Self;
method empty in trait Map of type => scala.collection.mutable.Map[K,V] has incompatible type;
(Note that method empty in trait ForwardingMutableMap of type => ForwardingMutableMap.this.Self is abstract,
and is therefore overridden by concrete method empty in trait Map of type => scala.collection.mutable.Map[K,V])
trait ForwardingMutableMap[K, V, +Self <: mutable.MapLike[K, V, Self] with mutable.Map[K, V]]
第三次尝试:
trait ForwardingMutableMap[K, V, +Self <: mutable.MapLike[K, V, Self] with mutable.Map[K, V]]
extends mutable.Map[K, V]
with mutable.MapLike[K, V, Self] { this: Self =>
override def empty: Self = empty2
def empty2: Self
protected val delegate: mutable.Map[K, V]
def get(key: K): Option[V] = delegate.get(key)
def iterator: Iterator[(K, V)] = delegate.iterator
def -=(key: K): this.type = {
delegate -= key
this
}
def +=(kv: (K, V)): this.type = {
delegate += kv
this
}
}
类型混合ForwardingMutableMap
必须实现empty2
而不是empty
.
这行得通,但有一股黑客的味道。我能做得更好吗?