views:

61

answers:

1

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 parameter of setter underlying_=
+5  A: 

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.

retronym