The fold method assumes an associative operator and can theoretically (for example, when using parallelism) be executed in random order. Thus, the signature makes it clear that the type of accumulation must be a supertype of the collection element:
def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1
The deduced supertype (String, Int) and Int is Any .
All of this is described in the API documentation .
What you want is foldLeft or foldRight , which do not have this type restriction:
def foldLeft[B](z: B)(f: (B, A) ⇒ B): B
Thus:
l.foldLeft(0) { (acc, tup) => acc + tup._2 }
or
(0 /: l) { case (acc, (_, n)) => acc + n }
source share