Scala Option: Usage of unless with getOrElse

381 views Asked by At

I have an Option of string, say O, which can be empty. And there is a condition, say cond. My requirement is to construct Option of the value inside O if cond is true, else None. I do this:

Option.unless(cond)(o.getOrElse(None))

Is this a correct functional way of doing it? Or there can be a better/cleaner/easy to understand way?

1

There are 1 answers

0
Tim On

As pointed out in the comments, the answer is to use filter:

o.filter(_ => cond)

The condition in a filter does not have to use the value that is passed to it, but can be any expression that returns a Boolean.