2014-04-03 41 views
2

我的代碼中有一個可變變量,我想通過使用某些聚合函數來避免。不幸的是,我找不到解決方案以下僞代碼。如何使用reduce或fold來避免可變狀態

def someMethods(someArgs) = { 
     var someMutableVariable = factory 

     val resources = getResourcesForVariable(someMutableVariable) 
     resources foreach (resource => { 
      val localTempVariable = getSomeOtherVariable(resource) 
      someMutableVariable = chooseBetteVariable(someMutableVariable, localTempVariable) 
     }) 

     someMutableVariable 
    } 

我在我的代碼中有兩處地方,我需要建立一些變量,然後在循環與其他可能性進行比較,如果差那麼這個新的可能性替換它。

回答

5

如果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) 
} 

,然後你沒有可變狀態。

+0

這就是爲什麼我愛斯卡拉。 – squixy