以下を考えると:
trait Fruit
class Apple extends Fruit
class Orange extends Fruit
case class Crate[T](value:T)
def p(c:Crate[Fruit]) { }
val cra = Crate(new Apple)
val cro = Crate(new Orange)
Crate は不変であるため、次のことはできません (予想どおり)。
scala> val fruit:Crate[Fruit] = cra
<console>:10: error: type mismatch;
found : Crate[Apple]
required: Crate[Fruit]
val fruit:Crate[Fruit] = cra
^
scala> val fruit:Crate[Fruit] = cro
<console>:10: error: type mismatch;
found : Crate[Orange]
required: Crate[Fruit]
val fruit:Crate[Fruit] = cro
scala> p(cra)
<console>:12: error: type mismatch;
found : Crate[Apple]
required: Crate[Fruit]
p(cra)
^
scala> p(cro)
<console>:12: error: type mismatch;
found : Crate[Orange]
required: Crate[Fruit]
p(cro)
しかし、Crate が共変でないのに、なぜこれらでメソッド p を呼び出せるのでしょうか? :
scala> p(Crate(new Apple))
Crate(line2$object$$iw$$iw$Apple@35427e6e)
scala> p(Crate(new Orange))
Crate(line3$object$$iw$$iw$Orange@33dfeb30)
分散の基本原則をいくつか見逃していませんか?