Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Blocks

We can embed a sequence of statements inside "try", called a "block". Defined variables are only visible within that block, not outside:

...

Code Block
def a = 123
try{
  try{
    try{
      assert a == 123
    }
  }
}

Closures

We can take a sequence of statements that refers to its external context and assign it to a variable, then execute it later. It's technically called a "closable block", commonly called a "closure":

...

Code Block
c = { def e = { 'milk' }; e }
d = c
assert c == d
v1 = c()
v2 = c()
assert v1 != v2

Closure Parameters

We can put parameters at the beginning of a closure definition, and pass values in when we call the closure:

...

Code Block
def gcd //predefine closure name
gcd={ m,n-> m%n==0? n: gcd(n,m%n) }
assert gcd( 28, 35 ) == 7

Functions

A function is similar to a closure, though a function can't access defined variables in its surrounding context:

...

Code Block
def f(){
  //def g1(){ println 'there' }
      //a compile error when uncommented: can't nest functions
  'here'
}
assert f() == 'here'
try{
  //def g2(){ println 'yonder' }
      //a compile error when uncommented: can't nest functions
}
c = {
  //def g3(){ println 'outer space' }
      //a compile error when uncommented: can't nest functions
}
def h(){
  try{ def c = { 'here, again' } }
      //we can have blocks and closures within functions
}

Function Parameters

A function can have parameters, with which we can pass information both in and out:

...

Code Block
def c(){'method c'}
def c= {-> 'closure c'}
assert c() == 'method c'

def d(i){'method d'}
def d= {'closure d'}
assert d(9) == 'method d'

Some Similarities with Closures

We can use the shortcut invocation syntax for closure parameters:

...