Is there a scala identity function?

前端 未结 3 481
生来不讨喜
生来不讨喜 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:39

    There's an identity function in Predef.

    l flatMap identity[Option[String]]
    
    > List[String] = List(Hello, World)
    

    A for expresion is nicer, I suppose:

    for(x <- l; y <- x) yield y
    

    Edit:

    I tried to figure out why the the type parameter (Option[String]) is needed. The problem seems to be the type conversion from Option[T] to Iterable[T].

    If you define the identity function as:

    l.flatMap( x => Option.option2Iterable(identity(x)))
    

    the type parameter can be omitted.

提交回复
热议问题