Operator Overloading in Groovy Step 12
Another shortcut in Groovy isOperator Overloading.
You can type something like this:
def d = new Date()
println d.next()
(1..3).each{println d++}
This code will print:
Mon Jan 11 12:06:11 PST 2010
Sun Jan 10 12:06:11 PST 2010
Mon Jan 11 12:06:11 PST 2010
Tue Jan 12 12:06:11 PST 2010
assuming that today’s date is January 10th at 12:06 PST in 2010.
This code will instatiate a new date and print the next date.
Then it will print three more dates starting from today’s date.
The d++ will call the next method.
Here are other operator overloading:
| Operator | Method |
| a==b or a!=b | a.equals(b) |
| a + b | a.plus(b) |
| a-b | a.minus(b) |
| a*b | a.multiply(b) |
| a/b | a.div(b) |
| a%b | a.mod(b) |
| a++ or ++a | a.next() |
| a– or –a | a.previous() |
| a & b | a.and(b) |
| a | b | a.or(b) |
| a[b] | a.getAt(b) |
| a[b]=c | a.putAt(b,c) |
| a<<b | a.leftShift(b) |
| a>>b | aa.rightShift(b) |
| a<b or a>b or a<=b or a>=b | a.compareTo(b) |
For example:
def b=new Date()
def v = new Date()
println “b”+b
println “v”+d
if(b.equals(v))
println “true”
else
println “false”
Tweet This Post
Plurk This Post
Buzz This Post
Delicious This Post
Digg This Post
Ping This Post
Reddit This Post
Stumble This Post
No Comments »
No comments yet.
RSS feed for comments on this post.