scala - val a : Set[Fruit]=Set[Apple]() does not compile, 为什么?如何修复?

标签 scala generics

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/

相关文章:

mysql - 光滑的代码生成器不包括带表的模式

java - 扩展像 ArrayList 这样的 Java 集合类以更轻松地进行泛型管理(警告...等)?

scala - Scala中 '_'(下划线)作为类型变量的理解

java - 什么时候在 Scala 中使用惰性值?

java - 什么是原始类型,为什么我们不应该使用它呢?

c# - 为什么 Generic Casting 不适用于这部分代码?

c# - 将类型参数传递给用于指定泛型类型的方法

Java 通用接口(interface)返回类型

Scala 捕获由 future 序列引发的错误

scala - 连接 2 个大型 DF 时 Spark : Size exceeds Integer. MAX_VALUE