Wednesday, April 25, 2012

scala map / type instantiation

can someone explain the best way to get around the following,
rather curious type error. Suppose I create a list of tuples like so:



scala> val ys = List((1,2), (3,4), (5,6))
ys: List[(Int, Int)] = List((1,2), (3,4), (5,6))


Now, if I want to map this to a List(Int)



scala> ys.map((a: Int, b: Int) => a + b)
<console>:9: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => ?
ys.map((a: Int, b: Int) => a + b)
^


Any clues? I know I can use the for comprehension



scala> for ((a, b) <- ys) yield a + b
res1: List[Int] = List(3, 7, 11)


But it feels wrong to bust out a comprehension in this setting. Thanks!





No comments:

Post a Comment