下面的类型T
是Fruit
的子类型。 Apple
也是Fruit
的子类型。那么,为什么在下面使用类型归属时,编译器不会将Apple强制转换为T.为什么我们需要一个明确的演员才能使其工作?推断类型时,强制规则是什么?子类型和类型强制
trait Fruit
case class Apple(id: String) extends Fruit
type T <: Fruit
val t: T = Apple("apple") // why doesn't the compiler coerce Apple to T?
val t: T = Apple("apple").asInstanceOf[T] // works!
所以,“Pear <:胎儿”意味着Pear是'胎儿的**特定**亚型和**特定**亚型不是'Apple'?但是,为什么'梨'不能成为'苹果'?所有编译器都知道'Pear'是'Fetus'的子类型。它可以或不可以是Apple。 – Samar
我更新了答案 –
感谢您的回答,现在有道理。 – Samar