将Scala与一组子类型相交
发布时间:2020-12-16 09:57:39 所属栏目:安全 来源:网络整理
导读:为什么这个函数不能编译? 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] Not
为什么这个函数不能编译?
case class MyType(n: Int) def intersection(s1: Set[MyType],s2: Set[_ <: MyType]) = (s1 & s2) 我收到以下错误:
是否有一种简单的方法可以“提升”第二个参数来键入Set [MyType]而不使用asInstanceOf? 解决方法
Set在其类型参数上不协变.
所以一个简单的解决方案是转换为List(这是协变的): def intersection(s1: Set[MyType],s2: Set[_ <: MyType]) = s1.toList.intersect(s2.toList).toSet (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |