开发者

How to implement collection with covariance when delegating to another collection for storage?

I'm trying to implement a type of SortedMap with extended semantics. I'm trying to delegate to SortedMap as the storage but can't get around the variance constraints:

class IntervalMap[A, +B](implicit val ordering: Ordering[A])
    //extends ...
{
  var underlying = SortedMap.empty[A, List[B]]
}

Here is the error I get. I understand why I get the error (I understand variance). What I don't get is how to implement this type of delegation. And yes, the covariance on B is required.

error: covariant type B occurs in contravariant position in type scala.collection.immutable.SortedMap[A,List[B]] of 开发者_如何学JAVAparameter of setter underlying_=


You can't make underlying a var, but you can make it a val.

scala> import collection._
import collection._

scala> class IntervalMap[A, +B](implicit val ordering: Ordering[A]) {
     |   val underlying = SortedMap.empty[A, List[B]]
     | }
defined class IntervalMap

In your example, var defines a pair of methods:

class IntervalMap[A, +B](implicit val ordering: Ordering[A]) {
  def underlying_=(s: SortedMap[A, List[B]]) = // ...
  def underlying: SortedMap[A, List[B]]) = // ...
}

For the type parameter B to be appear in both an input and an output, it must be invariant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜