Sunday, January 10, 2010

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:


OperatorMethod
a==b or a!=ba.equals(b)
a + ba.plus(b)
a-ba.minus(b)
a*ba.multiply(b)
a/ba.div(b)
a%ba.mod(b)
a++ or ++aa.next()
a-- or --aa.previous()
a & ba.and(b)
a | ba.or(b)
a[b]a.getAt(b)
a[b]=ca.putAt(b,c)
a<<ba.leftShift(b)
a>>baa.rightShift(b)
a<b or a>b or a<=b or a>=ba.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"

0 comments: