我有以下型號:接入領域
abstract class Shape(x1: Int, y1: Int, x2: Int, y2: Int)
case class Line(x1: Int, y1: Int, x2: Int, y2: Int) extends Shape(x1, y1, x2, y2)
case class Rectangle(x1: Int, y1: Int, x2: Int, y2: Int) extends Shape(x1, y1, x2, y2)
我這樣做處理:
val shapes: scala.collection.mutable.Queue[Shape] = mutable.Queue.empty[Shape]
shapes.foreach(shape => {
(shape.x1 until shape.x2).foreach(x => if(0 <= x && x < canvas.width && 0 <= shape.y1 && shape.y1 < canvas.height) {
board(x)(shape.y1) = 'X'
})
})
我評估每個Shape
以同樣的方式,不管它是否是一個Line
或Rectangle
。然而,我無法訪問abstract class
領域:
Error:(90, 14) value x1 is not a member of Shape
(shape.x1 until shape.x2).foreach(x => if(0 <= x && x < canvas.width && 0 <= shape.y1 && shape.y1 < canvas.height) {
^
我會做一個Shape
case class
,後來我就無法將其與Line
和Rectangle
延伸。
在這種情況下設計模型的最優雅方式是什麼?
我想我需要允許:
- 基類的擴展。
- 訪問基類的字段。
您在'x's和'y'之前缺少'val's。 –