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

scala – val a:设置[Fruit] =设置[Apple]()不编译,为什么?怎

发布时间:2020-12-16 09:06:46 所属栏目:安全 来源:网络整理
导读:行val a:设置[Fruit] = Set [Apple]不编译,为什么? 怎么解决这个问题? package sandbox.stackOverFlowclass Fruit class Apple extends Fruitclass Banana extends Fruitclass Why{ val a:Set[Fruit]=Set[Apple]() // Does not compile,why ? val b:List[
行val a:设置[Fruit] = Set [Apple]不编译,为什么?

怎么解决这个问题?

package sandbox.stackOverFlow

class Fruit 
class Apple extends Fruit
class Banana extends Fruit

class Why{
  val a:Set[Fruit]=Set[Apple]() // Does not compile,why ?
  val b:List[Fruit]=List[Apple]() // Does compile.
}

产生编译错误:

type mismatch;
 found   : scala.collection.immutable.Set[sandbox.stackOverFlow.Apple]
 required: Set[sandbox.stackOverFlow.Fruit]
Note: sandbox.stackOverFlow.Apple <: sandbox.stackOverFlow.Fruit,but trait Set is invariant in type A.
You may wish to investigate a wildcard type such as `_ <: sandbox.stackOverFlow.Fruit`. (SLS 3.2.10)
  val a:Set[Fruit]=Set[Apple]()
                         ^

编辑:

正如Jatin的回答所指出的,这个问题已在这里得到解答:Why is Scala’s immutable Set not covariant in its type?

解决方法

Set(甚至不可变)的类型参数是不变的(主要是因为Set [A]继承自A => Boolean,这是A中的反对变体). List的类型参数是协变的.

至于如何解决这个问题,编译器为您提供了一个潜在的解决方案:使用通配符,例如

val a: Set[_ <: Fruit] = Set[Apple]()

(编辑:李大同)

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

    推荐文章
      热点阅读