10
votes

Why does this code result in the compilation error

type mismatch; found : (Int, Char) required: scala.collection.GenTraversableOnce[?]

?

val n = Map(1 -> 'a', 4 -> 'a')
def f(i: Int, c: Char) = (i -> c) 
n.flatMap (e => f(e._1, e._2))
1

1 Answers

10
votes

Use map() instead:

n.map (e => f(e._1, e._2))

flatMap() assumes you are returning a collection of values rather than a single element. Thus these would work:

n.flatMap (e => List(f(e._1, e._2))
n.flatMap (e => List(f(e._1, e._2), f(e._1 * 10, e._2)))

The second example is interesting. For each [key, value] pair we return two pairs which are then merged, so the result is:

Map(1 -> a, 10 -> a, 4 -> a, 40 -> a)