Un-optioning an optioned Option

后端 未结 6 1145
甜味超标
甜味超标 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:10

    You could use scalaz join to do this, as this is one of the monadic operations:

    doubleOpt.join
    

    Here it is in the REPL:

    scala> import scalaz._; import Scalaz._
    import scalaz._
    import Scalaz._
    
    scala> some(some("X")).join
    res0: Option[java.lang.String] = Some(X)
    
    scala> some(none[String]).join
    res1: Option[String] = None
    
    scala> none[Option[String]].join
    res3: Option[String] = None
    

    It's available to anything with a typeclass instance for a Monad.

提交回复
热议问题