codeology
codeology

Reputation: 357

How to determine which condition is false in an if statement

I have an if statement like so:

if(a > b && b < c) && (c > d && d < e) && (e > f && f < g)

Is there a way to find out which specific condition in the if statement is false in Scala 2.12? For example (c > d && d < e) is false, or simply (e > f) is false.

Upvotes: 0

Views: 226

Answers (2)

Volty De Qua
Volty De Qua

Reputation: 290

val r = Seq(a > b && b < c, c > d && d < e, e > f && f < g)
if (!reduce(_ && _)) println(r.indexOf(false))

or. to find all of them

r.zipWithIndex.filter(!_._1).map(_._2)

Upvotes: 0

Instead of if, you can use pattern matching.
Something like:

((a > b), (b < c), (c > d), (d < e), (e > f), (f < g)) match {
  case (false, false, false, false, false) => // all failed.
  case (false, false, false, false, true) => // all but last failed.
  ...
  case (true, true, true, true, true) => // all succeed.
}

You can tune the logic to your specific problem.

Upvotes: 3

Related Questions