我正在尝试使用扩展语义实现一种SortedMap.我正在尝试将SortedMap委托为存储,但无法绕过方差约束:
class IntervalMap[A, +B](implicit val ordering: Ordering[A])
//extends ...
{
var underlying = SortedMap.empty[A, List[B]]
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误.我理解为什么我得到错误(我理解方差).我没有得到的是如何实现这种类型的委托.是的,B上的协方差是必需的.
error: covariant type B occurs in contravariant position in type scala.collection.immutable.SortedMap[A,List[B]] of parameter of setter underlying_=
Run Code Online (Sandbox Code Playgroud)
你不能制作底层的var,但你可以成为一个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
Run Code Online (Sandbox Code Playgroud)
在您的示例中,var定义了一对方法:
class IntervalMap[A, +B](implicit val ordering: Ordering[A]) {
def underlying_=(s: SortedMap[A, List[B]]) = // ...
def underlying: SortedMap[A, List[B]]) = // ...
}
Run Code Online (Sandbox Code Playgroud)
要使type参数B同时出现在输入和输出中,它必须是不变的.