g9023734
g9023734

Reputation: 11

Groovy ifs - how to do it better (rewriting code from Java to Groovy)

Let's assume that we have such code in java:

if(A) { return X }
if(B) { return Y }
return Z

How to rewrite it in groovy?

We can't write like this because it isn't working. We can also write like this:

if(A) {    
   return X
}
else {
 if(B) return Y
 else return Z
}

but it isn't quite elegant. Any ideas?

Upvotes: 1

Views: 283

Answers (1)

Opal
Opal

Reputation: 84756

It can be done with ternary operator:

def X = 1
def Y = 2
def Z = 3

def A = null
def B = 1

assert 2 == A ? X : B ? Y : Z

A = 1
B = null

assert 1 == A ? X : B ? Y : Z

A = null
B = null

assert 3 == A ? X : B ? Y : Z

Upvotes: 2

Related Questions