liuxu
liuxu

Reputation: 37

How to put multiple variables in groovy switch statement?

How to put multiple variables in groovy switch statement? eg. The if any variable is false, it will print "false" orelse print "true". The following script doesn't work

a=true
b=true
c=true
switch(true)
{
 case(a==true && b==true && c==true)
   println("true")
   break
 case(a==false || b==false || c==false)
   println("false")
   break   
}

Upvotes: 1

Views: 759

Answers (3)

ulidtko
ulidtko

Reputation: 15642

You can use groovy.lang.Tuple:

a = true
b = true
c = true
switch (new Tuple(a, b, c)) {
  case [new Tuple(true, true, true)]:
    println "All true!"
    break
  case [new Tuple(true, false, true)]:
    println "b is false"
    break
  default:
    println "Something else"
}

One caveat here: bizarrely, Tuple extends java.util.AbstractList thus is an iterable "collection", AbstractList. And if you pass a collection in case label — groovy will try to do an "in list" element membership check. Meaning switch ("bar") { case ["foo", "bar", "buzz"]: ...} — will trigger.

For this reason, you need to wrap the concrete tuples in case-labels into a singleton list:
case [new Tuple(true, true, true)] not case new Tuple(true, true, true).

Upvotes: 0

seansand
seansand

Reputation: 1504

You could do something like the following, create a function that combines the three variables and switch on that. But I would not recommend it; the combination function is an unnecessary new element that could easily be buggy. You're better off using a series of if/else statements.

a = true
b = true
c = true

switch(a.toString() + b.toString() + c.toString())
{
   case "truetruetrue":
     println("true")
     break
   case "falsefalsefalse":
     println("false")
     break   
   default:
     println("a different combination")
     break
}

The above in Groovy Web Console

Upvotes: 0

zett42
zett42

Reputation: 27806

The switch statement is for testing a single value against multiple conditions.

While the switch statement is versatile, when testing multiple variables, a plain old if/else is more appropriate:

if( a && b && c ) { println 'true' }
else              { println 'false' }

Alternatively you may use the in (membership) operator. It tests if the LHS operand (value) is contained in the RHS operand (collection).

if( false in [a,b,c] ) { println 'false' }
else                   { println 'true' }

Upvotes: 1

Related Questions