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!
try:
or:
What’s happening is that
ysis aListof(Int,Int), somapexpects a function from a single argument, which happens to be a tuple(Int,Int), to something else (technically,mapexpects an argument ofFunction1[(Int,Int),Int]. The function(a: Int, b: Int) => a+bis not actually a function from a single argument(Int, Int)toInt; instead it’s a function of two arguments, bothInts, to anInt(aFunction2[Int,Int,Int]). The difference is subtle, but important since Scala makes a distinction:To explain my suggestions at the top of the answer: In the first example, we have changed the definition of the function given to
mapto usecase, which tells Scala to unpack the single(Int,Int)argument into its two parts. (Note also the use of curly braces instead of parentheses.) In the second example, we have a function of a single tuple argument,p, and we manually extract each part of the tuple.Finally, note that you don’t need the type annotations either. These work just as well: