我是 scala 的新手并且遇到了一些继承问题......我的 NodeVisitor 类无法区分 GreenBasket 中的“b1”和“b2”,并提供错误说明 Basket 中没有“访问”方法。GreenBasket 必须能够容纳带有“b1”和“b2”的 GreenBasket 或 OrangeBasket 对象。如何根据“b1”和“b2”的类型调用适当的“访问”方法?谢谢你。
trait Visitor{
def visit(o: OrangeBasket): Int
def visit(g: GreenBasket): Int
}
sealed abstract class Basket() {
def accept(visitor: Visitor): Unit
}
case class OrangeBasket(count: Int, kilos: Double) extends Basket(){
def this(count: Int) = this(count, 0)
def accept(visitor: Visitor) = visitor.visit(this)
}
case class GreenBasket(b1: Basket, b2: Basket) extends Basket(){
def this(b1: Basket) = this(b1, null)
def this() = this(null)
def accept(visitor: Visitor) = visitor.visit(this)
}
class NodeVisitor() extends Visitor{
def visit(o: OrangeBasket) = 1
def visit(g: GreenBasket) = this.visit(g.b1) + this.visit(g.b2) + 1
}