Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: how to avoid mutation?

Tags:

scala

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?

like image 985
Vadim Samokhin Avatar asked Mar 15 '26 06:03

Vadim Samokhin


1 Answers

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.

like image 129
Daniel C. Sobral Avatar answered Mar 17 '26 23:03

Daniel C. Sobral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!