Versions Compared

Key

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

...

Java does know classwide variables and local variables. Local variables are defined as method parameter or inside the method block. Classwide variables are defined as attributes of the class. Of course Java does violate this first principle I showed at top here a little since I can access class wide varibales variables from outside the class, if the access modifier is for example public. A local variable of the same name as an attribute does not violate the second principle, as the attribute is hidden by the local variable and with this no longer visible without using a qualifier like "this".

...

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

...