0

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?

Artemis
  • 2,553
  • 7
  • 21
  • 36
Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • 5
    `o.filter(_ => cond)` ? Or if you have **cats** `o.whenA(cond)` – Luis Miguel Mejía Suárez Jun 21 '21 at 15:53
  • Thanks. Seems lot to learn in Scala. – Mandroid Jun 21 '21 at 15:56
  • 5
    There's a lot of ways to do things in Scala, and it's generally OK to not know every bit right away. – Levi Ramsey Jun 21 '21 at 16:12
  • 4
    To add to @LeviRamsey, it's really functional programming in general that there is a lot to learn, Scala is just a tool for doing FP. You would likely perform nearly the same thing in Haskell or even Java using their `Optional`. Tough to know everything about FP, I admittedly don't. It does take time, just keep chipping away at it. – Daniel Hinojosa Jun 21 '21 at 17:33

1 Answers1

1

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.

Tim
  • 26,753
  • 2
  • 16
  • 29