这是用Akka类型创建本地参与者变量的正确方法(参见名为var的state)吗?
示例:
object Main {
def behavior(name: String): Behavior[String] = {
var state = s"$name's state."
Static {
case str: String =>
println(s"$name: Updating state.")
state = state + str
println(s"$name: State is now $state")
}
}
def main(args: Array[String]): Unit = {
def mainBe: Behavior[String] =
ContextAware {
context =>
val a1 = context.spawn(Props(behavior("Actor 1")), "actor-1")
val a2 = context.spawn(Props(behavior("Actor 2")), "actor-2")
Static {
case str =>
a1 ! str + "(1)"
a2 ! str + "(2)"
}
}
val system = ActorSystem("Tester", Props(mainBe))
system ! "John"
system ! "Smith"
Await.result(system.whenTerminated, 1 second)
}
}输出:
Actor 1: Updating state.
Actor 2: Updating state.
Actor 1: State is now Actor 1's state.John(1)
Actor 2: State is now Actor 2's state.John(2)
Actor 1: Updating state.
Actor 2: Updating state.
Actor 1: State is now Actor 1's state.John(1)Smith(1)
Actor 2: State is now Actor 2's state.John(2)Smith(2)发布于 2015-12-21 20:49:57
是的,这是正确的方法。但是,依赖可变变量并不总是更好,在许多情况下,必须分配新行为的性能开销不如对不可变行为给您带来的简单编程错误的改进弹性那么重要。你的例子看起来应该是:
def behavior(name: String) = behavior(name, s"$name’s state.")
def behavior(name: String, state: String): Behavior[String] =
Total { str =>
println(s"$name: Updating state.")
val nextState = state + str
println(s"$name: State is now $nextState")
behavior(name, nextState)
}无法用新值更新引用意味着编译器将限制您可能做错的事情(比如更新两次或根本不更新)。
https://stackoverflow.com/questions/34388131
复制相似问题