I got a small snippet of Scala code that I'd like to optimize to be more functional.
I got the following
val foo: Option[Double]
val bar: Map[String, Double]
And a method which takes an Option[Map[String, Double]]
So in my business logic, I try to determine if foo
is defined. If it is, I have to pass None
to the method, since both foo
and bar
cannot be simultaneously present.
I currently handle this in the following way
val newOptionalMap = if (foo.isDefined) {
None
} else {
Some(bar)
}
myFunction(newOptionalMap)
I'd like to turn this into a more functional approach. I tried with
val newOptionalMap = foo.map(_ => bar)
But this is failing, since it's never actually defining bar
as None
, thus my method fails as it doesn't expect both foo
and bar
to be simultaneously defined.
Which functional approach could I take to simplify the conditional logic?
CodePudding user response:
There are two way to handle your problem.
As stated by @jwvh you can easly used fold
:
val newOptionalMap = foo.fold(Option(bar))(_ => None))
Another way could be using pattern matching:
val newOptionalMap = foo match {
case Some(_) => None
case _ => Some(bar)
}
Here there is a discussion about fold or pattern matching usage,