Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested "if"/"match" statement in scala: better approach?

I have a series of validation functions that returns an Option[Problem], if any, or None if no validation problems are found. I would like to write a simple function that calls each validation function, stop and return the first not-None result.

Naturally I can write this method in the "java-style", but I would like to know if a better approach exists.

EDIT

This was the original Java solution:

validate01(arg);
validate02(arg);
validate03(arg);
...

Each method throws an exception in case of problem. I would stay away from the exceptions while I'm writing Scala.

like image 813
Marco Avatar asked Dec 12 '22 19:12

Marco


1 Answers

As an example, let's say we want to validate a String. Our validation function takes a String and a list of validators, which are functions from String to Option[Problem]. We can implement it in a functional manner like this:

def firstProblem(validators: List[String => Option[Problem]], s:String) =
  validators.view.flatMap(_(s)).headOption

This creates a new list by applying each validation function to the string and keeping the result only if it is a Some. We then take the first element of this List. Because of the call to view, the list will be computed only as needed. So as soon as the first Problem is found, no further validators will be called.

like image 75
Kim Stebel Avatar answered Jan 04 '23 11:01

Kim Stebel