Groovy: how to simplify / rewrite this method in groovy

protected int xMethod (Integer a, Integer b) {
  if (a<b)
    return 1
  else if (a>b)
    return 2
  else
    return 3
}

I wonder if there is a way to rewrite the above method differently in groovy? since now it is very java style.

+5
source share
4 answers

It seems that the functions just need to return 3 different values โ€‹โ€‹depending on whether it is less, equal to or greater than b. Groovy already has a statement that does this:

a <=> b

The return values โ€‹โ€‹are -1, 0, and 1. It might be best to reorganize the code to use this operator instead of xMethod, if possible.

Of course, if the exact values โ€‹โ€‹1, 2 and 3 are important, and not just 3 different values, you cannot do this.

+2
source

Just to expand Mark's answer:

protected int xMethod (Integer a, Integer b) {
    switch ( a <=> b ) {
       case -1: 1; break
       case  1: 2; break
       case  0: 3; break
    }
}

, - . , -1, 0, 1, .

+1

:  return (a <=> b) + 2

0

Integer, , < .

.

assert x.xMethod (1, 2) == 1
assert x.xMethod ("2", "1") == 2
assert x.xMethod (2.0, 2.0) == 3

0
source

All Articles