Search code examples
scalamutation

scala: how to avoid mutation?


It is a commonplace when one needs to accumulate some data. The way I get used to do it is appending data chunks to array. But it's a bad practice in scala, so how can I avoid it?


Solution

  • Well, there are two generic ways of dealing with accumulation: recursion and folding. Let's look into very simple examples of each, to compute the sum of values of a list.

    def sumRecursively(list: List[Int]): Int = {
      def recurse(list: List[Int], acc: Int): Int =
        if (list.isEmpty) acc
        else recurse(list.tail, acc + list.head)
      recurse(list, 0)
    }
    
    def sumFolding(list: List[Int]): Int =
      list.foldLeft(0){ case (acc, n) => acc + n }
    

    There are many variations on this, which handle better one case or another.