blog rss feed

Groovy part 2 - focusing on the language

Keywords:

Last editor: Dave Cherry, last modified: Aug 3, 2008

Groovy how to - Part 2

In the previous groovy article I gave you a feel for the groovy language, showing you how to deal with strings, objects and do basic iteration. In this article I go into a little more detail about looping and how the type system works.

Ranges - ranges can be treated as collections

A range is a sequence of numbers either inclusive or exclusive. Ranges are used in many places in the groovy language, so getting an understanding of them is important. A range is a sequence of numbers, either inclusive or exclusive. Please see the example below.

  • 0..10 range of 0 to 10 inclusive.
  • 1..9 range of 1 to 9 inclusive
  • 1..<9 range of 1 to 8 (exclusive of 9)
  • [0..10] range of numbers 0 to 10 inclusive as a List

If statements - allow non boolean conditions

In comparison with java, groovy if statements allow a wider range of conditions. For example references are considered false when null, integers are considered false when 0.

def ref = null
def
val = 10;
if( ! ref)
{
println
"null"
}

if( val )
{
println
"not zero"
}

While statement - not much change from Java

While is pretty much the same as the java equivalent, except that the condition does not have to be boolean as per the if statement.

def val = 10;
while( val )
{
println val;
val--;
}

For statement - iterate over ranges and iterables.

For statements are quite different from Java, but I think for the better as they are much more readable. In essence a for statement is an iteration over a range or iterable (such as list). See the examples below.

// notice this is a range - ie no []
for (i in 1..5)
{
println
"for loop ${i}"
}
for(i in [1,4,6,8,9])
{
println i;
}
1 2 3 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30