相交Scala设置与子类型的集合 [英] Intersect Scala set with set of subtype

查看:234
本文介绍了相交Scala设置与子类型的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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?

解决方案



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

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


Why doesn't this function compile?

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

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

Is there a simple way to "promote" the second argument to type Set[MyType] without using asInstanceOf?

解决方案

A Set is not covariant on its type parameter.

So a simple solution is to convert to List (which is covariant):

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

这篇关于相交Scala设置与子类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆