Scala-akka:在receive函数中声明一个全局变量

Scala-akka:在receive函数中声明一个全局变量,scala,functional-programming,akka,Scala,Functional Programming,Akka,我想在参与者收到一些消息时声明一个全局变量,这是我的代码,它可以工作。问:我能用不可变变量实现吗 case class Start(configs:JobConfig) trait Job extends Actor with ActorLogging { //use "val" instead private var confMap:Map[String,String]=Map() def receive = { case Start(conf) => {

我想在参与者收到一些消息时声明一个全局变量,这是我的代码,它可以工作。问:我能用不可变变量实现吗

case class Start(configs:JobConfig)
trait Job extends Actor with ActorLogging {
  //use "val" instead
  private var confMap:Map[String,String]=Map()
  def receive = {
    case Start(conf) => {
      confMap = conf.properties
      init()
    }
      case x => log.debug("Got: " + x)
  }

  final def getProperties():Map[String,String]={
    confMap
  }

  def init()

}

当然可以,但是如果您的
init
使用
confMap
它应该将map作为参数:

...
def receive(confMap:Map[String,String] = Map()) = {
  case Start(conf) => 
    init(conf.properties)
    context.become(receive(conf.properties))
  case ...

您可以找到更多信息

谢谢您的回复。但是如何在其他函数中使用confMap?我不知道哪个函数将使用confMap,这是我声明全局变量的主要原因。如果使用全局变量,则会产生副作用。孤立地测试您的函数变得很困难,有时甚至不可能。因此,我认为您的所有函数都应该以
confMap
作为参数,或者您可以创建一个类,该类将以configs作为参数,并具有您需要的所有方法,并在
receive
参数中使用它。