user282436
user282436

Reputation:

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 some way of rewriting above method differently in groovy? as now is very Java style.

Upvotes: 5

Views: 450

Answers (4)

slim
slim

Reputation: 41223

Just to expand on 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
    }
}

However, you have to question whether this method has any value. If the caller can be changed to accept -1, 0, 1 then the method has no reason to exist.

Upvotes: 1

Philip Schwarz
Philip Schwarz

Reputation: 1

If you remove the two occurrences of Integer from the signature, you can call the method with any parameters for which < is defined.

E.g.

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

Upvotes: 0

jamz
jamz

Reputation: 5311

How about: return (a <=> b) + 2

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838156

It seems that the function just needs to return 3 different values depending on whether a is less than, equal to, or greater than b. There is already an operator in Groovy that does this:

a <=> b

The return values are -1, 0 and 1. Perhaps the best thing to do is refactor the code to use this operator instead of xMethod, if that is possible.

Of course, if the precise values 1, 2 and 3 are important and not just 3 distinct values then you can't do this.

Upvotes: 2

Related Questions