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.
followed by a bunch of characters to get me up to the minimum that stackoverflow allows
I think the conversion to the Iterable is just fine. Use these steps to go from
Option[Option[String]
to a singleOption[String]
(which returns
Option[String]
)Well, I actually don't understand how come it could be just None (the third case). If it can really be also just None, then I would vote for Rex Kerr's answer, otherwise just .get would be enough:
You might use flatMap like the following:
This will map the
List[Option[Option[Int]]]
to aList[Option[Int]]
.If you just have an Option you can use it as following:
This will flatten your
Option[Option[Int]]
toOption[Int]
.It's a shame thatflatten
doesn't exist. It should.Flatten does exist now.
As before,
(in addition to the other answers) will also do the same thing.
You could use scalaz
join
to do this, as this is one of the monadic operations:Here it is in the REPL:
It's available to anything with a typeclass instance for a Monad.