Un-optioning an optioned Option

Knut Arne Vedaa picture Knut Arne Vedaa · May 11, 2011 · Viewed 9.9k times · Source

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.

Answer

Rex Kerr picture Rex Kerr · May 11, 2011

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.