Search code examples
scalafunctional-programmingimmutabilityvar

Scala - How to avoid a var here


I wonder if anybody knows how to avoid the var in the following pseudocode:

var cnt = theConstant
val theSequence = theMap.flapMap{case (theSet, theList) =>
  if (theSet.isEmpty) {
    // do something here with theList and return a sequence
  } else {
    cnt += 1
    // do something here with cnt and theList and return a sequence
  }}

Solution

  • This type of thing is done with foldLeft. It starts with whatever initial value you give it as an argument, and then calls your function for each element of the collection with a tuple, where first element is the previous result of function evaluation (or the initial value), and the second one is the current element of the collection.

    val (cnt, theSequence) = theMap.foldLeft(0 -> Nil) { 
      case ((cnt, seq), (set, list)) if set.isEmpty => (cnt, seq ++ whateverSequence) 
      case ((cnt, seq), (set, list)) => (cnt + 1, seq ++ whateverSequence)
    }
    

    You can also use a recursive solution:

    @tailrec 
    def countAndSeq[K,V,T](in: List[(Set[K], List[V]], cnt: Int = 0, seq: List[T] = Nil) = in match {
      case Nil => cnt -> seq
      case (set, list) :: tail if set.isEmpty => countAndSeq(tail, cnt, seq ++ whatever)
      case (set, list) :: tail => countAndSeq(tail, cnt+1, seq ++ whatever)
    

    }

    val (cnt, seq) = countAndSeq(theMap.toList)