Scala - 如何在这里避免使用 var

Scala - How to avoid a var here

我想知道是否有人知道如何避免以下伪代码中的 var:

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

这种事情是用foldLeft做的。 它以你给它的任何初始值作为参数开始,然后用一个元组为集合中的每个元素调用你的函数,其中第一个元素是函数评估的先前结果(或初始值),第二个是集合的当前元素。

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

您还可以使用递归解决方案:

@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)