我有以下课程模型:
sealed abstract class Tile(val coordinate: Int, val isOccupied: Boolean) {
def isEmpty() : Boolean
def getPiece() : Option[Piece]
}
case class EmptyTile(coordinate: Int) extends Tile(coordinate, false) {
override def toString: String = "" +coordinate
override def isEmpty() = true
override def getPiece() = None
}
case class OccupiedTile(coordinate: Int, val piece: Piece) extends Tile(coordinate, true) {
override def toString = piece.toString
override def isEmpty = false
override def getPiece = Some(piece)
}
我收到以下错误:
Error:(6, 22) overriding value coordinate in class Tile of type Int;
value coordinate needs `override' modifier
case class EmptyTile(coordinate: Int) extends Tile(coordinate, false) {
^
我究竟做错了什么?
编辑:请求查看Piece类,在这里添加:
import Alliance.Alliance
import PieceType.PieceType
abstract class Piece(val piecePosition: Int, val pieceType : PieceType, val alliance: Alliance) extends Movable {
}
object PieceType extends Enumeration {
type PieceType = Value
val PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING = Value
}
最佳答案
您的抽象类Tile
声明一个val coordinate
,使该值可公开访问。您的案例类EmptyTile
也隐式地将coordinate
声明为val(案例类“ magic”)。基本上,您的case类实际上是在尝试覆盖抽象类已经提供的值。
您可以在抽象类声明中删除val
,也可以不创建EmptyTile
和OccupiedTile
案例类。
编辑:评论后建议的替代方案:
trait Tile {
def coordinate: Int
def isOccupied: Boolean
def isEmpty() : Boolean = !isOccupied
def getPiece() : Option[Piece]
}
case class EmptyTile(coordinate: Int) extends Tile {
override def toString: String = "" +coordinate
val isOccupied = false
def getPiece() = None
}
case class OccupiedTile(coordinate: Int, val piece: Piece) extends Tile {
override def toString = piece.toString
val isOccupied = true
def getPiece = Some(piece)
}
关于scala - Scala中具有构造函数参数的抽象类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24703786/