Scala中带有构造函数参数的抽象类

时间:2014-07-11 18:00:23

标签: scala

我有以下类模型:

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
}

2 个答案:

答案 0 :(得分:5)

您的抽象类Tile声明val coordinate,使此值可公开访问。您的案例类EmptyTile也隐含地将coordinate声明为val(案例类" magic")。基本上,您的case类有效地尝试覆盖抽象类已经提供的值。

您可以删除抽象类声明中的val,也可以不删除EmptyTileOccupiedTile个案例类。

编辑:评论后建议的备选方案:

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)
}

答案 1 :(得分:1)

case class自动生成其参数val。这就是为什么论述coordinateEmptyTile,理解为val coordinate,与抽象类的val coordinate冲突。

解决此问题的一种方法是在coordinate中将isOccupiedTile定义为摘要。 Tile甚至可以是一个特征而不是抽象类:

sealed trait Tile {
  def coordinate: Int
  def isOccupied: Boolean
  ...
}

case class EmptyTile(coordinate: Int) extends Tile {
  def isOccupied = false
  ...
}

case class OccupiedTile(coordinate: Int, piece: Piece) extends Tile {
  def isOccupied = true
  ...
}