Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala type mismatch error, GenTraversableOnce[?] required

Tags:

scala

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))
like image 803
Vadim Samokhin Avatar asked Jan 26 '13 17:01

Vadim Samokhin


1 Answers

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)
like image 88
Tomasz Nurkiewicz Avatar answered Oct 17 '22 07:10

Tomasz Nurkiewicz