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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With