Effective way to case match a tuples with boolean values in scala

Viewed 382

I want to case match tuples which contain boolean values. Is there an effective way to match the results as case match on boolean looksexhautive

val ABC= "abc"
val DEF = "def"

private def istest1 = true
private def istest2 = true
private def istest3 = true

(istest1, istest2, istest3) match {

  case (true, true, true)=>ABC
  case (false, true, true) =>DEF
  case (false , false , true)=> //print something else

  //other cases
} 
3 Answers

You need to have a statement for each of the possible outcomes, and using match seems to be the most compact and readable way to do it.

One possible improvement is to use _ for "don't care" values:

(istest1, istest2, istest3) match {
  case (true, true, true) => ABC
  case (_, true, true) => DEF
  case (false, _, true) => //print something 
  case _ =>  //other cases
}

There may be performance issues with different versions of these tests, but it is best to pick the one that makes the most sense. Aim for readability and maintainability above perceived performance.

Your approach seems fine, but given all of your values are boolean you could use some stable identifiers to name them and make the code a bit more readable

val ABC = "abc"
val DEF = "def"

def isTest1 = true
def isTest2 = true
def isTest3 = true

val PassedTest1 = true
val PassedTest2 = true
val PassedTest3 = true

val NotPassedTest1 = false
val NotPassedTest2 = false

(isTest1, isTest2, isTest3) match {

    case (PassedTest1, PassedTest2, PassedTest3)       => ABC
    case (NotPassedTest1, _, PassedTest3)    => DEF
    case (NotPassedTest1, NotPassedTest2, PassedTest3) => //print something
    case _                                             => ???
  }

Also as @Tim mentioned, you can use _ to match any value inside the tuple, or to match any tuple as the last case so you don't have to be exaustive

I would even go one step further to Brunos solution:

sealed trait PassedOrNot {
  final val Passed    = true
  final val NotPassed = false
}

case object Test1 extends PassedOrNot
case object Test2 extends PassedOrNot
case object Test3 extends PassedOrNot

def isTest1 = true
def isTest2 = true
def isTest3 = true

(isTest1, isTest2, isTest3) match {
  // @formatter:off
  case (Test1.Passed   , Test2.Passed, Test3.NotPassed) => ???
  case (Test1.NotPassed, _           , Test3.NotPassed) => ???
  case _                                                => ???
  // @formatter:on
}
Related