Scala Iterable#map与Iterable#flatMap [英] scala Iterable#map vs. Iterable#flatMap
本文介绍了Scala Iterable#map与Iterable#flatMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Iterable
的map
和flatMap
函数之间有什么区别?
What is the difference between the map
and flatMap
functions of Iterable
?
推荐答案
以下是一个很好的解释:
Here is a pretty good explanation:
http://www. codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
以列表为例:
地图的签名是:
map [B](f : (A) => B) : List[B]
和flatMap是
flatMap [B](f : (A) => Iterable[B]) : List[B]
因此,flatMap采用类型[A]并返回可迭代类型[B],地图采用类型[A]并返回类型[B]
So flatMap takes a type [A] and returns an iterable type [B] and map takes a type [A] and returns a type [B]
这还将使您了解平面图将拉平"列表.
This will also give you an idea that flatmap will "flatten" lists.
val l = List(List(1,2,3), List(2,3,4))
println(l.map(_.toString)) // changes type from list to string
// prints List(List(1, 2, 3), List(2, 3, 4))
println(l.flatMap(x => x)) // "changes" type list to iterable
// prints List(1, 2, 3, 2, 3, 4)
这篇关于Scala Iterable#map与Iterable#flatMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文