Scala foldLeft on Maps

Pengin picture Pengin · Nov 14, 2010 · Viewed 27.1k times · Source

How do you use Map.foldLeft? According to the docs it looks like

foldLeft [B] (z: B)(op: (B, (A, B)) ⇒ B) : B

But I'm having difficulty:

Map("first"->1,"second"->2).foldLeft(0)((a,(k,v)) => a+v )

error: not a legal formal parameter

The error points to the open bracket in front of k.

Answer

Debilski picture Debilski · Nov 14, 2010

If you want to use the (a, (k, v)) syntax, you need to advise the compiler to use pattern matching.

Map("first"->1, "second"->2).foldLeft(0){ case (a, (k, v)) => a+v }

Note that a case statement requires curly braces.