Saturday, January 16, 2010

Groovy Autoboxing Step 14

In Java, primitives were used for speed and objects were used for developers convenience. In Groovy, everything is an Object.

if you type:

def i=2
println i.class
==> java.lang.Integer

def d=2.2
println d.class
==>java.math.BigDecimal

You do not need to worry about declaring your variable in Groovy because Groovy will automatically know what class your variable is. Groovy will autobox everything on the fly. You can call methods on what looks like a primitive, when it is actually a class. Primitives no longer exist in Groovy.

The good news is that in Groovy, if you give a number a decimal, it will autobox to a BigDecimal instead of a floating point number. This will avoid the dreaded "floating-point arithmetic" problem in Java.

0 comments: