List of options: equivalent of sequence in Scala?

后端 未结 7 634
别那么骄傲
别那么骄傲 2021-01-04 04:55

What is the equivalent of Haskell\'s sequence in Scala? I want to turn list of options into an option of list. It should come out as None if any of the options

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 05:48

    This is very simple with a for comprehension:

    val x : Option[String] = Option("x")
    val y : Option[String] = Option("y")
    val z : Option[String] = None
    
    // Result -> a: Option[List[String]] = None    
    val a = for {
      x <- x
      y <- y
      z <- z
    } yield List(x,y,z)    
    
    // Result -> b: Option[List[String]] = Some(List(x, y))    
    val b = for {
      x <- x
      y <- y
    } yield List(x,y)
    

提交回复
热议问题