相交Scala设置与子类型的集合 [英] Intersect Scala set with set of subtype
问题描述
case class MyType(n:Int)
def intersection s1:设置[MyType],s2:设置[_<:MyType])=
(s1& s2)
我得到以下错误:
error:type mismatch;找到:Set [_ $ 1]其中type _ $ 1
<:MyType required:scala.collection.GenSet [MyType]注意:_ $ 1<:
MyType,但特征GenSet在类型A中不变。您可能希望
调查通配符类型,如_<:MyType
。 (SLS 3.2.10)
(w& r)
有没有一种简单的方法来促销第二种参数类型Set [MyType]而不使用asInstanceOf?
所以一个简单的解决方案是转换为 Why doesn't this function compile? I get the following error: error: type mismatch; found : Set[_$1] where type _$1
<: MyType required: scala.collection.GenSet[MyType] Note: _$1 <:
MyType, but trait GenSet is invariant in type A. You may wish to
investigate a wildcard type such as Is there a simple way to "promote" the second argument to type Set[MyType] without using asInstanceOf? A So a simple solution is to convert to
这篇关于相交Scala设置与子类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
List
(它是协变的):
def intersection(s1:Set [MyType],s2:Set [_<:MyType])=
s1.toList.intersect(s2.toList).toSet
case class MyType(n: Int)
def intersection(s1: Set[MyType], s2: Set[_ <: MyType]) =
(s1 & s2)
_ <: MyType
. (SLS 3.2.10)
(w & r)Set
is not covariant on its type parameter.List
(which is covariant):def intersection(s1: Set[MyType], s2: Set[_ <: MyType]) =
s1.toList.intersect(s2.toList).toSet