行 val a: Set[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]()
关于scala - val a : Set[Fruit]=Set[Apple]() does not compile, 为什么?如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22399823/