The line val a: Set[Fruit]=Set[Apple]
does not compile, why ?
How can this be fixed ?
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.
}
Produces compile error:
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]()
^
EDIT:
As pointed out in Jatin's answer, this question is answered already here : Why is Scala's immutable Set not covariant in its type?