Java Reference
In-Depth Information
Groovy handles that issue without a problem. Here's the analogous Groovy script:
println 2.0 - 1.1
The answer in this case is 0.9, as expected. Because the calculations are done with
BigDecimal
, the answer is correct. Groovy also has operator overloading, so the plus
operator can be used with the
BigDecimal
values. To summarize:
Literals
Numbers without a decimal point are of type
Integer
,
Long
, or
java.math.BigInteger
, depending on size. Numbers with a decimal point are of
type
java.math.BigDecimal.
Because numbers are objects, they have methods as well.
Listing B.2
shows a script putting
some numbers through their paces. Several of the expressions use closures, which are the
subject of
section B.4
.
The simplest definition is to consider them a block of code that's
executed as though it's an anonymous method call.
Listing B.2.
numbers.groovy
, showing method calls on numeric literals
assert 2**3 == 8
assert 2**-2 == 0.25 // i.e., 1/(2*2) = 1/4
def x = ""
3.times { x += "Hello" }
assert x == "HelloHelloHello"
def total = 0
1.upto(3) { total += it }
assert total == 1 + 2 + 3
def countDown = []
5.downto 1, { countDown << "$it ..." }
assert countDown == ['5 ...', '4 ...', '3 ...', '2 ...', '1 ...']
Groovy has an exponentiation operator, unlike Java. Numbers have methods like
times
,
upto
, and
downto
. The
times
operation takes a single argument of type
Closure
.
When the last argument to a method is a closure, you can put it after the parentheses. Be-
cause the method has no other arguments, you can leave out the parentheses altogether.