flatten和flatMap(identity)有什么区别吗? [英] Is there any difference between flatten and flatMap(identity)?
本文介绍了flatten和flatMap(identity)有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
scala> List(List(1), List(2), List(3), List(4))
res18: List[List[Int]] = List(List(1), List(2), List(3), List(4))
scala> res18.flatten
res19: List[Int] = List(1, 2, 3, 4)
scala> res18.flatMap(identity)
res20: List[Int] = List(1, 2, 3, 4)
这两个函数有什么区别吗?什么时候适合使用其中一种?是否有权衡?
Is there any difference between these two functions? When is it appropriate to use one over the other? Are there any tradeoffs?
推荐答案
您可以查看 flatMap(identity)
作为地图(标识).flatten
。 (当然,它不会以这种方式实现,因为它需要两次迭代)。
You can view flatMap(identity)
as map(identity).flatten
. (Of course it is not implemented that way, since it would take two iterations).
map(identity)
为您提供相同的集合,因此最终它与 flatten
。
map(identity)
gives you the same collection, so in the end it is the same as only flatten
.
我个人坚持 flatten
,因为它更短/更容易理解,并设计为准确做到这一点。
I would personally stick to flatten
, since it is shorter/easier to understand and designed to exactly do this.
这篇关于flatten和flatMap(identity)有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文