For understanding, only syntactic sugar is understood for the flatMap , map and filter series. Let desugar your code then:
val theBoolean = Some(false) val x = theBoolean.map { theArg => if (theArg) { "abc" } else { None } }
As you can see, you are simply matching the Option value, so you will either return Some(abc) , Some(None) or None (in case theBoolean already None ).
The lowest common type is None and "abc" is java.Serializable , so type x is output as Option[Serializable] , which is pointless like Option[Any] .
Possible solutions:
using flatMap
theBoolean.flatMap(theArg => if (theArg) Some("abc") else None)
or even shorter
theBoolean.flatMap(if (_) Some("abc") else None)
filtering and display
theBoolean.withFilter(identity).map(_ => "abc")
Where I used identity , since you are testing the value itself.
It is clear that you can always use the syntactic sugar provided for understanding, although in fact it does not really matter.
for { theArg <- theBoolean if theArg } yield "abc"
source share