Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Collections, Lists, etc.

Why don't return statements work when iterating through an object?

The {...} in an each statement is not a normal Java block of code, but a closure. Closures are like classes/methods, so returning from one simply exits out of the closure, not the enclosing method.

How do I declare and initialize a list at the same time?

Syntax:

Code Block
def x = [ "a", "b" ]

How do I declare and initialize a traditional array at the same time?

Syntax:

Code Block
String[] x = [ "a", "qrs" ]

or

Code Block
String[] x = [ "a", "qrs" ] as String[]

or

Code Block
def x = [ "a", "qrs" ] as String[]

Why does myMap.size or myMap.class return null?

In Groovy, maps override the dot operator to behave the same as the index[ ] operator:

Code Block
myMap["size"]="ONE MILLION!!!";
println myMap.size        // outputs 'ONE MILLION!!!'

//use the following:
println myMap.@size       // '1'
println myMap.size()      // '1'
println myMap.getClass()  // 'class java.util.HashMap'

Why is my map returning null values?

Chances are, you tried to use a variable as a key in a map literal definition.
Remember, keys are interpreted as literal strings:

Code Block
myMap = [myVar:"one"]
assert myMap[ "myVar" ] == "one"

Try this (note the parentheses around the key):

Code Block
myMap = [(myVar):"one"]