0

以下 Scala 代码给出了一个编译错误,指出我无法分配给 val:

简化示例:

class State {
  val a = 1
  val b = 2

  def compute( res: =>Int, add : Int ): Unit = {
    res = add + 123456
  }

  compute(a,b)
  compute(b,a)
}

更接近我实际用途的示例:

class Editor {
  var str:String = ""
  var cursor:Int = 0

  case class UndoState(str:String, cursor:Int)

  var undoState = Seq[UndoState]()
  var redoState = Seq[UndoState]()

  def undo(): Unit = if (undoState.nonEmpty) {
    redoState = UndoState(str,cursor) +: redoState
    str = undoState.head.str
    cursor = undoState.head.cursor
    undoState = undoState.tail
  }

  def redo(): Unit = if (redoState.nonEmpty) {
    undoState = UndoState(str,cursor) +: undoState
    str = redoState.head.str
    cursor = redoState.head.cursor
    redoState = redoState.tail
  }
}

由于撤消/重做都非常相似,我想将公共代码提取到一个函数中,我想将源/目标对作为redoState/传递undoState,反之亦然。

有什么方法可以告诉函数应该在哪里存储一些东西?(在 C++ 中,在这种情况下我会传递一个指向成员的指针)。

4

3 回答 3

1

使用返回值:

def compute( add : Int ): Int = {
  add + 123456
}

val a = compute(b)
val b = compute(a)

像在 C++ 中那样通过引用传递不能在 Scala 中完成,而且通常也不是您想要做的。但是,您可以传递一个包含对可变字段的引用的容器:

class Box(var value: Int)

def compute( box: Box, add : Box): Unit = {
  box.value = add.value + 123456
}

val a = new Box(1)
val b = new Box(2)
compute(a, b)
compute(b, a)

或(略有不同)使compute成员成为Box

class Box(var value: Int) {
  def compute(add: Box): Unit = {
    value = add.value + 123456
  }
}

val a = new Box(1)
val b = new Box(2)
a.compute(b)
b.compute(a)
于 2015-01-22T13:23:53.950 回答
1

您可以使您的状态(可变)堆栈而不是(不可变)序列,并将它们传递给一个通用函数来操作:

  def undoredo(states: (Stack[UndoState], Stack[UndoState])): Unit = states match {
      case (Stack(), _) => ()
      case (from, to) => 
          to.push(UndoState(str,cursor))
          val state = from.pop
          str = state.str
          cursor = state.cursor              
  }

  def undo() = undoredo(undoState -> redoState)
  def redo() = undoredo(redoState -> undoState)

或者,如果您喜欢 scala 的“类 DSL”功能,您可以通过以下方式以有趣的方式执行此操作:

implicit class StateStack(from: Stack[UndoState]) {
    def ->(to: Stack[UndoState]): Unit = if(from.nonEmpty) {  
        to.push(UndoState(str,cursor)) 
        val state = from.pop
        str = state.str
        cursor = state.cursor            
    }
  }

然后,您可以执行undoState -> redoState“撤消”或redoState -> undoState“重做”之类的操作...

于 2015-01-22T15:07:40.543 回答
1

您可以创建和传递函数来设置新状态(撤消或重做):

...
var undoState = Seq[UndoState]()
var redoState = Seq[UndoState]()

def anywaydo(set: (Seq[UndoState]) => Unit) {
  set(...)
  ...
}

def undo {
  anywaydo((state) => undoState = state)
}
于 2015-01-22T13:57:33.393 回答