scala 类型不匹配错误,需要 GenTraversableOnce[?]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14539701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:52:37  来源:igfitidea点击:

scala type mismatch error, GenTraversableOnce[?] required

scala

提问by Vadim Samokhin

Why does this code result in the compilation error

为什么这段代码会导致编译错误

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

类型不匹配; 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))

采纳答案by Tomasz Nurkiewicz

Use map()instead:

使用map()来代替:

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:

flatMap()假设您返回的是一组值而不是单个元素。因此,这些将起作用:

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:

第二个例子很有趣。对于每个 [key, value] 对,我们返回两对然后合并,因此结果是:

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