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]() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 为Ruby On Rails环境创建Docker镜像时出
- AngularJS – Google将ui-sref映射到标记内
- 角度 – 在ng服务上获取错误:错误无法读取未定义的属性“l
- 在Scala中,是否可以使用类型,但不允许使用像Haskell这样的别
- 【数据结构】邓玉欣的编程作业indexing
- angular – 为什么[class.someClass]和[ngClass]绑定与myOb
- angularjs解决方案之 递归模板
- WebService之CXF注解报错(一)
- angularjs 前端js正则表达式的运用
- scala – Spark – 如何读取csv文件作为DataFrame?