我想到用Like
特質讓你細化回報(表示)類型。這涉及更多的工作。比較:
import collection.generic.CanBuildFrom
object FooMap {
type Coll = FooMap[_, _]
implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), FooMap[A, B]] = ???
}
trait FooMap[A, +B] extends Map[A, B] {
def foo = 33
}
def test(f: FooMap[Any, Any]) {
f.map(identity).foo // nope, we ended up with a regular `Map`
}
與
object FooMap extends collection.generic.ImmutableMapFactory[FooMap] {
override type Coll = FooMap[_, _]
implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), FooMap[A, B]] = ???
def empty[A, B]: FooMap[A, B] = ???
}
trait FooMap[A, +B] extends Map[A, B]
with collection.immutable.MapLike[A, B, FooMap[A, B]] {
def foo = 33
override def empty: FooMap[A, B] = FooMap.empty[A, B]
}
def test(f: FooMap[Any, Any]) {
f.map(identity).foo // yes
}
的MapLike
特質必須Map
特質後混合在正確的返回類型踢
你仍然沒有得到。似乎免費的一切,例如您將需要覆蓋更多方法:
override def +[B1 >: B](kv: (A, B1)): FooMap[A, B1] // etc.