문제

I have a mutable variable in my code that I want to avoid by using some of aggregation function. Unfortunatelly I couldn't find solution for the following pseudocode.

    def someMethods(someArgs) = {
      var someMutableVariable = factory

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

        someMutableVariable
    }

I have two places in my code where I need to build some variable, then in loop compare it with other possibilities and if it worse then replace it with this newly possibility.

도움이 되었습니까?

해결책

If you resources variable supports it:

 //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) 
 }

and then you don't have mutable state.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top