以下 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++ 中,在这种情况下我会传递一个指向成员的指针)。