Iterable的map函数和flatMap函数有什么不同
发布于 2009-06-29 20:33:13
这里有一个很好的解释:
http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-2
以list为例:
Map的签名是:
map [B](f : (A) => B) : List[B]而flatMap的是
flatMap [B](f : (A) => Iterable[B]) : List[B]因此,flatMap采用类型A并返回可迭代类型B,而map采用类型A并返回类型B
这也会给你一个想法,扁平图将“扁平化”列表。
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)发布于 2009-06-29 20:37:50
以上都是正确的,但还有一件事很方便:flatMap将List[Option[A]]转换为List[A],并删除任何深入到None的Option。这是超越使用null的一个关键的概念突破。
发布于 2009-06-29 18:40:00
来自scaladoc
返回通过将给定函数f应用于此迭代器的每个元素而得到的迭代器。
将给定的函数f应用于此迭代器的每个元素,然后连接结果。
https://stackoverflow.com/questions/1059776
复制相似问题