我具有以下特征:
sealed trait Move extends AbstractCommand {
def execute(): Option[State] = {
this match {
case MoveLeft(state) => shiftCursorCharacter(-1, state)
case MoveRight(state) => shiftCursorCharacter(1, state)
case MoveUp(state) => shiftCursorLine(-1, state)
case MoveDown(state) => shiftCursorLine(1, state)
}
}
def copy(newState: State): Move = {
this match {
case MoveLeft(_) => MoveLeft(newState)
case MoveRight(_) => MoveRight(newState)
case MoveRightAndPast(_) => MoveRightAndPast(newState)
case MoveUp(_) => MoveUp(newState)
}
}
case class MoveLeft(state: State) extends Move
case class MoveRight (state: State) extends Move
case class MoveRightAndPast (state: State) extends Move
case class MoveDown (state: State) extends Move
case class MoveUp (state: State) extends Move
AbstractCommand
看起来像这样:
abstract trait AbstractCommand {
val state: State
def execute(): Option[State]
}
当然,我还有其他类型的命令(扩展AbstractCommand
),它们也具有state和execute
def。我是Scala的新手。对于案例类,我无法使用内置的复制方法(无法真正理解原因)。我想知道是否有一个
A)更好的方法(更通用)来编写复制方法,好像我添加了新的Move命令一样,它们都具有相同的复制行为:我想更改状态但保留命令类型,或者
B)(有一个更好的设计可以结合这个想法)(我已经尝试过,但是没有找到替代方法)。