makerGeek makerGeek - 1 year ago 62
Scala Question

scala returns list of empty

I'm trying to sum the values of the pairs that have the same character, but when printing, i get


here's my code

var lstA = List(("a",1),("b",2))
var lstB = List(("a",3), ("b",4))

val k = => lstB.foreach(b => {
if(b._1 == a._1) (a._1, a._2+b._2) else a


of course there are better ways to do this, but I just want to know why this isn't working.
when debugging and evaluating the line
if(b._1 == a._1) (a._1, a._2+b._2) else a
i get the values of pairs as expected however when printing the list
is empty

Answer Source

The short and not entirely accurate answer is because foreach doesn't return anything. Actually, though, it does return something. Here is the signature:

def foreach[U](f: (A) ⇒ U): Unit

It returns a Unit type, which is used as a signal that the function has side-effects. From the documentation, the f parameter is:

the function that is applied for its side-effect to every element. The result of function f is discarded.

So the function is expected to have a side effect. This could be something like println.