加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

将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)

我收到以下错误:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读