Given the following:
val x = Some(Some(1))
What would be the cleanest way to get the 1 (or -1 if the one did not exist)?
I'm creating an object instance from a tuple returned from a database query. One of the values in the tuple looks like this, so I would like a nice short 'one liner' to just get the value or set a parameter to -1.
x.flatten
is what you are looking for. Here it will give you Some(1)
.
If you really want to get -1
for the case where "the one did not exist", just do x.flatten.getOrElse(-1)
:
scala> Some(Some(1)).flatten.getOrElse(-1)
res1: Int = 1
scala> Some(None).flatten.getOrElse(-1)
res2: Int = -1
scala> None.flatten.getOrElse(-1)
res3: Int = -1
for-comprehensions are often a very readable way to use these kinds of nested structures:
val x = Some(Some(1))
val result = for {
firstLevel <- x
secondLevel <- firstLevel
} yield {
// We've got an int, now transform it!
(secondLevel * 100).toString
}
The result is an Option[String], and the transformation only happens when you have two Some(s).
You can also use pattern matching:
val result2 = for {
Some(v) <- x
} yield {
// We've got a int, now transform it!
(v * 100).toString
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With