Un-optioning an optioned Option

后端 未结 6 1207
甜味超标
甜味超标 2021-02-02 07:05

Say I have a val s: Option[Option[String]]. It can thus have the following values:

Some(Some(\"foo\")) Some(None) None

6条回答
  •  渐次进展
    2021-02-02 07:08

    You might use flatMap like the following:

    val options = List(Some(Some(1)), Some(None), None)
    options map (_ flatMap (a => a))
    

    This will map the List[Option[Option[Int]]] to a List[Option[Int]].
    If you just have an Option you can use it as following:

    val option = Some(Some(2))
    val unzippedOption = option flatMap (b => b)
    

    This will flatten your Option[Option[Int]] to Option[Int].

提交回复
热议问题