Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Un-optioning an optioned Option

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

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

I want to reduce it so that the first becomes Some("foo") while the two others become None. Obviously there are many ways to accomplish this, but I'm looking for a simple, perhaps built-in, less-than-one-liner.

like image 962
Knut Arne Vedaa Avatar asked May 11 '11 17:05

Knut Arne Vedaa


Video Answer


2 Answers

It's a shame that flatten doesn't exist. It should.

Flatten does exist now.

As before,

s getOrElse None 

(in addition to the other answers) will also do the same thing.

like image 146
Rex Kerr Avatar answered Oct 05 '22 22:10

Rex Kerr


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.

like image 34
oxbow_lakes Avatar answered Oct 05 '22 22:10

oxbow_lakes