How to call .map() on a list of pairs in Scala
You can use pattern matching to get the elements of the pair.
ll.map{ case (x:Int,y:Int) => x + y }
You don't even need to specify the types:
ll.map{ case (x, y) => x + y }
The same works with foreach
of course.
The error message tells you that the compiler expected to find a function of one parameter (a pair of ints) to any type (the question mark) and instead found a function of two parameters, both ints.
You can tuple a function, which means going from one that takes N args to one that takes 1 arg that is an N-tuple. The higher-order function to do this is available on the Function
object. This results in nice syntax plus the extra type safety highlighted in the comments to Brian Agnew's answer.
import Function.tupled
ll map tupled(_ + _)
You can use:
ll.map(x => x._1 + x._2)
where x
stands for the tuple itself, or
ll.map(x:(Int,Int) => x._1 + x._2)
if you want to declare the types explicitly.