Is there a scala identity function?

前端 未结 3 445
生来不讨喜
生来不讨喜 2021-02-04 23:13

If I have something like a List[Option[A]] and I want to convert this into a List[A], the standard way is to use flatMap:

         


        
3条回答
  •  春和景丽
    2021-02-04 23:55

    FWIW, on Scala 2.8 you just call flatten on it. Thomas has it mostly covered for Scala 2.7. He only missed one alternative way of using that identity:

    l.flatMap[String](identity)
    

    It won't work with operator notation, however (it seems operator notation does not accept type parameters, which is good to know).

    You can also call flatten on Scala 2.7 (on a List, at least), but it won't be able to do anything without a type. However, this works:

    l.flatten[String]
    

提交回复
热议问题