Professional Documents
Culture Documents
Documentation
Operator Overloading
Operator Overloading
Groovy/Grails Tool Suite
www.Grails.org/GGT S
The Groovy programming language is supported by Pivotal and the Groovy Community
Groovy supports operator overloading which makes working with Numbers, Collections, Maps and various other data structures easier to use. Various operators in Groovy are mapped onto regular Java method calls on objects. This allows you the developer to provide your own Java or Groovy objects which can take advantage of operator overloading. The following table describes the operators supported in Groovy and the methods they map to. Operator a+b a-b a*b a ** b a/b a%b a|b a&b a ^b a++ or ++a a-- or --a a[b] a[b] = c a << b a >> b switch(a) { case(b) : } ~a -a +a Method a.plus(b) a.minus(b) a.multiply(b) a.power(b) a.div(b) a.mod(b) a.or(b) a.and(b) a.xor(b) a.next() a.previous() a.getAt(b) a.putAt(b, c) a.leftShift(b) a.rightShift(b) b.isCase(a) a.bitwiseNegate() a.negative() a.positive() buy at Amazon buy at Amazon
Information
News FAQ Roadmap Eclipse plugin
Books ...
International
Note that all the following comparison operators handle nulls gracefully avoiding the throwing of java.lang.NullPointerException
Groovy Operator
a == b a != b a <=> b a>b a >= b a<b a <= b
IDE Support
Download
About
Search
a.equals(b) or a.compareTo(b) == 0 ** ! a.equals(b) a.compareTo(b) a.compareTo(b) > 0 a.compareTo(b) >= 0 a.compareTo(b) < 0 a.compareTo(b) <= 0
Feeds
Site News
** Note: The == operator doesn't always exactly match the .equals() method. You can think of them as equivalent in most situations. In situations where two objects might be thought "equal" via normal Groovy "coercion" mechanisms, the == operator will report them as equal; the .equals() method will not do so if doing so would break the normal rules Java has
groovy.codehaus.org/Operator+Overloading
1/2
18/10/13
around the equals method. Expect further improvements to Groovy over time to provide clearer, more powerful and more consistent behavior in this area.
In addition when comparing numbers of different types the type coercion rules apply to convert numbers to the largest numeric type before the comparison. So the following is valid in Groovy
B y t ea=1 2 D o u b l eb=1 0 a s s e r tai n s t a n c e o fB y t e a s s e r tbi n s t a n c e o fD o u b l e a s s e r ta>b
groovy.codehaus.org/Operator+Overloading
2/2