如何避免使用变量

如何将这段代码转换为功能方法?在Akka中,我看到了Aktor :: become()方法,该方法可以覆盖行为。我怎样才能取得类似的成绩?

class Updater {
  var move: String = ""
  val step = 50

  def handler(key: KeyEvent) = {
    if (key.getCode.equals(KeyCode.Up.delegate)) move = "up"
    if (key.getCode.equals(KeyCode.Down.delegate)) move = "down"
    if (key.getCode.equals(KeyCode.Left.delegate)) move = "left"
    if (key.getCode.equals(KeyCode.Right.delegate)) move = "right"
  }

  def update(state: State): State = {
    val result = move match  {
      case "up" => State(state.x, state.y - step)
      case "down" => State(state.x, state.y + step)
      case "left" => State(state.x - step, state.y)
      case "right" => State(state.x + step, state.y)
      case _ => state
    }

    move = ""
    result
  }
}
评论