Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala make multiple option checks more concise

Working with Options in Scala and Play Framework, is there a more concise way of checking x amount of variables like so?

if (a.isDefined || b.isDefined || c.isDefined || d.isDefined ...) {

}

Is a one liner something like (a,b,c,d).isDefined possible?

Thanks

like image 488
bluedaniel Avatar asked Dec 08 '22 06:12

bluedaniel


1 Answers

On top of my head, probably there's a nicer way:

List(a, b, c, d).exists(_.isDefined)

For ands (from Rob Starling comment):

List(a, b, c, d).forall(_.isDefined)

You could also have more complex condition compositions:

// (a || b) && (c || d)
List(
  List(a, b).exists(_.isDefined), 
  List(c, d).exists(_.isDefined)
).forall(identity)

// (a && b) || (c && d)
List(
  List(a, b).forall(_.isDefined), 
  List(c, d).forall(_.isDefined)
).exists(identity)

And so on.

like image 102
Ende Neu Avatar answered Dec 26 '22 17:12

Ende Neu