Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Removed outdated sentence

...

Code Block
titleExample of disallowed definition in scripts

String attribute = "bar"
void aMethod(){
  assert attribute == "bar" // Not allowed !
}
aMethod()

...

That's easy. When it is not defined, it is in the binding.

Code Block

String localVar = "I am a local variable"
bindingVar = "I am a binding variable"

...

Tip
titleRule of thumb

You can think of "def" as an alias of "Object" and you will understand it in an instant.

Future Groovy may give "def" an additional meaning in terms of static and dynamic typing. But this is post Groovy 1.0.
"def" can also replace "void" as the return type in a method definiton.

Code Block

def dynamic  =  1
dynamic = "I am a String stored in a variable of dynamic type"
int typed = 2
typed = "I am a String stored in a variable of type int??"    // throws ClassCastException

...

Code Block
titlea Java block

{
  int i=1;
  {
    System.out.println (i);
  }
}

...

Code Block
titleNot allowed

def closure = { int i; int i }

...

Code Block
titleinvalid double definition of variables

def outer = {
  int i
  def inner = { int i }
}

A block ends with its corresponding "}". So it is allowed to reuse that name later in a different block.

Code Block
titleAllowed

def closure1 = { parameter ->
  println parameter
}
def closure2 = { parameter ->
  println parameter
}

...

Code Block
titleimplicit it in closures

def c = { it }
assert c()  == null
assert c(1) == 1

When using nested cosures (closures in closures) the meaning of "it" depends on the closure you are in.

Code Block

def outer = {
  def inner = { it+1 }
  inner(it+1)
}
assert outer(1) == 3

...