package lecture13 import akka.actor.{Actor, ActorContext, ActorRef, ActorSystem, Props} import akka.event.LoggingReceive import akka.testkit.{ImplicitSender, TestKit} class CounterRight extends Actor: def counter(n: Int): Receive = { case "increment" => context.become(counter(n + 1), discardOld = false) // ^^^^^^^^^^^^^^^^^^ // This is needed. case "get" => sender() ! n case "decrement" => if n != 0 then context.unbecome() } def receive = counter(0) class CounterWrong extends Actor: def counter(n: Int): Receive = { case "increment" => context.become(counter(n + 1)) case "get" => sender() ! n case "decrement" => if n != 0 then context.unbecome() } def receive = counter(0) @main def becomeDemo() = new TestKit(ActorSystem("DebugSystem")) with ImplicitSender: try val counter = system.actorOf(Props(CounterRight()), "counter") counter ! "increment" counter ! "get" expectMsg(1) counter ! "increment" counter ! "get" expectMsg(2) counter ! "decrement" counter ! "get" expectMsg(1) // This is wrong if we use CounterWrong because it doesn't set the // discardOld parameter to false. Therefore, it will not remember the // previous state and reset the behavior to the initial one, which is // `counter(0)`. counter ! "decrement" counter ! "get" expectMsg(0) finally shutdown(system)