无法使对象不可变

时间:2013-05-27 10:30:16

标签: scala

我想调用服务器,但是当且仅当数据(在这种情况下为remoteIdKey)过时。我正是这样做的:

object remoteCaller {

 def getRemoteKeyId = {

   // do we need to get the data from the server?
   if (currentTime - lastCallTime >= 1000) {
      remoteId = makeRemoteCall
      lastCallTime = currentTime
    }

    remoteId
  }

  private var remoteId = 0
  private def currentTime = //....
  private var lastCallTime = //....
  private def makeRemoteCall = { //remote call to the server to get the remote Id key} 
}

问题是我改变了remoteCaller的状态,因此使用var代替val。而且我也想要使用对象而不是类来确保它只是它的实例。

如何使remoteCaller不可变或如何使用功能样式(没有变异)?

1 个答案:

答案 0 :(得分:1)

问题似乎是你想要实现两件互相排斥的东西:

  1. 可变状态
  2. object只有vals
  3. 正如@Felix已经说过的那样,具有可变状态本身并不是坏事。在你的情况下,我认为没关系,特别是如果它有助于避免不必要的复杂性。但是,你可以稍微清理一下。首先,我将你目前拥有的可变状态包装到一个新类中。例如:

    case class RemoteCall(remoteId: Int, lastCallTime: Int) {
        def refresh():RemoteCall = {
            if (currentTime - lastCallTime >= 1000) {
                RemoteCall(makeRemoteCall, currentTime)
            } else {
                this
            }
        }
    
        private def makeRemoteCall = { ... }
    }
    

    RemoteCaller对象中,您可以执行以下操作:

    object RemoteCaller {
    
        // Your entire mutable state wrapped in a case class
        private var remoteCall:RemoteCall = ...
    
        def getRemoteKeyId = {
            remoteCall = remoteCall.refresh
            remoteCall.remoteId
        }
    
    }