我想调用服务器,但是当且仅当数据(在这种情况下为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不可变或如何使用功能样式(没有变异)?
答案 0 :(得分:1)
问题似乎是你想要实现两件互相排斥的东西:
object
只有vals 正如@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
}
}