0

If I have an Option[Int] and a function validateInt(i: Int): Boolean. I want to do something if the option is empty or if it passes the validation.

I know it can be done with

if (opt.forall(validateInt)) {
   // do something
}

Is there a more functionally idiomatic way to do this in Scala?

uraza
  • 907
  • 4
  • 12
  • 22
  • 5
    Your code is functional and idiomatic. – Oleg Pyzhcov Feb 04 '19 at 12:26
  • @OlegPyzhcov The if statement is bugging me^^. Maybe I'm just code golfing too much – uraza Feb 04 '19 at 12:27
  • @uraza A bare `if` without an `else` implies non-functional code, so perhaps that is what is worrying you? (And for the purists, yes I know that this is not always true) – Tim Feb 04 '19 at 12:49
  • 1
    @Tim same can be said about any function returning `Unit` (since it implies side effects). Like `.foreach` :) – Dima Feb 04 '19 at 12:51

1 Answers1

4

opt.filterNot(validateInt).getOrElse(doStuff): Unit

But really, this does not look any better to my eye than your if statement.

Dima
  • 39,570
  • 6
  • 44
  • 70