为什么这个函数不能编译?
case class MyType(n: Int)
def intersection(s1: Set[MyType], s2: Set[_ <: MyType]) =
(s1 & s2)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
错误:类型不匹配; 找到:设置[_ $ 1]其中类型_ $ 1 <:MyType required:scala.collection.GenSet [MyType]注意:_ $ 1 <:MyType,但是特性GenSet在类型A中是不变的.您可能希望研究一个通配符类型作为
_ <: MyType.(SLS 3.2.10)(w&r)
是否有一种简单的方法可以"提升"第二个参数来键入Set [MyType]而不使用asInstanceOf?
ASet在其类型参数上不是协变的。
所以一个简单的解决方案是转换为List(这是协变的):
def intersection(s1: Set[MyType], s2: Set[_ <: MyType]) =
s1.toList.intersect(s2.toList).toSet
Run Code Online (Sandbox Code Playgroud)