【发布时间】:2018-09-07 06:12:53
【问题描述】:
我已经定义了一些 Scala 类:
class Drink
class SoftDrink extends Drink
class Cola extends SoftDrink
class VendingMachine[A](val currentItem: Option[A], items: List[A]) {
def this(items: List[A]) = this(None, items)
def addAll[B >: A](newItems: List[B]): VendingMachine[B] =
new VendingMachine(items ++ newItems)
}
然后我运行下面的代码sn-p:
val colasVM: VendingMachine[Cola] = new VendingMachine(List(new Cola, new Cola))
// It works
val softDrinksVM: VendingMachine[Drink] = colasVM.addAll(List(new SoftDrink))
// Compile Error: You may wish to define A as +A instead. (SLS 4.5)
val softDrinksVM2: VendingMachine[Drink] = new VendingMachine[SoftDrink](None, null)
在我看来,colasVM.addAll(List(new SoftDrink)) 返回VendingMachine[SoftDrink] 类型的数据,它不能分配给VendingMachine[Drink] 变量,因为它们不是同一类型。
但是val softDrinksVM: VendingMachine[Drink] = colasVM.addAll(List(new SoftDrink))在我这边可以编译成功,谁能帮忙解释一下为什么?
非常感谢!
【问题讨论】: