Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top