Is there any difference between flatten and flatMap(identity)?

后端 未结 3 1444
庸人自扰
庸人自扰 2020-12-16 23:44
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         


        
3条回答
  •  离开以前
    2020-12-17 00:23

    Conceptually, there is no difference. Practically, flatten is more efficient, and conveys a clearer intent.

    Generally, you don't use identity directly. It's more there for situations like it getting passed in as a parameter, or being set as a default. It's possible for the compiler to optimize it out, but you're risking a superfluous function call for every element.

    You would use flatMap when you need to do a map (with a function other than identity) immediately followed by a flatten.

提交回复
热议问题