我的代码中有一个可变变量,我想通过使用一些聚合函数来避免它。不幸的是我找不到以下伪代码的解决方案。
def someMethods(someArgs) = {
var someMutableVariable = factory
val resources = getResourcesForVariable(someMutableVariable)
resources foreach (resource => {
val localTempVariable = getSomeOtherVariable(resource)
someMutableVariable = chooseBetteVariable(someMutableVariable, localTempVariable)
})
someMutableVariable
}
我的代码中有两个地方需要构建一些变量,然后在循环中将其与其他可能性进行比较,如果情况更糟,则将其替换为这个新的可能性。
最佳答案
如果您的resources
变量支持它:
//This is the "currently best" and "next" in list being folded over
resources.foldLeft(factory)((cur, next) =>
val local = getSomeOther(next)
//Since this function returns the "best" between the two, you're solid
chooseBetter(local, cur)
}
然后你就没有可变状态了。
关于scala - 如何使用reduce或fold来避免可变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22839852/