将Scala与一组子类型相交

为什么这个函数不能编译?

case class MyType(n: Int)
def intersection(s1: Set[MyType],s2: Set[_ <: MyType]) =
  (s1 & s2)

我收到以下错误

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 _ <: MyType. (SLS 3.2.10)
(w & r)

是否有一种简单的方法可以“提升”第二个参数来键入Set [MyType]而不使用asInstanceOf?

解决方法

Set在其类型参数上不协变.

所以一个简单的解决方案是转换为List(这是协变的):

def intersection(s1: Set[MyType],s2: Set[_ <: MyType]) =
    s1.toList.intersect(s2.toList).toSet

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...