Closures, it and parameters

A closure is a block of code that can be stored in a variable, passed to a method and called later. Its literal is a pair of braces, and it is an object of the class groovy.lang.Closure.

The implicit it

it.groovy

def greet = { "Hello, ${it}" } println greet('Ada') println greet.call('Grace') println greet.class.name

groovy it.groovy

Hello, Ada
Hello, Grace
it$_run_closure1

A closure with one parameter that is not declared gets it. The two calls are the same call: a closure is invoked with parentheses, or with call when it is stored in a variable.

Declared and default parameters

params.groovy

def add = { int a, int b -> a + b } def power = { int base, int exponent = 2 -> base ** exponent } def nothing = { -> 'no arguments' } println add(2, 3) println power(3) println power(2, 8) println nothing()

groovy params.groovy

5
9
256
no arguments

A declared parameter may have a default, and the arrow separates the parameter list from the body when there is more than it. A closure with no parameter writes the arrow alone, which is how a reader knows that it is not used.

The value of a closure

return.groovy

def classify = { int n -> if (n < 0) { 'negative' } else if (n == 0) { 'zero' } else { 'positive' } } println classify(-2) println classify(0) println classify(7) def twice = { int n -> n * 2 } println([1, 2, 3].collect(twice))

groovy return.groovy

negative
zero
positive
[2, 4, 6]

The value of the last expression is the value of the closure, so a branch at the end returns from it. A closure is an object, which is why it can be passed to collect like any other argument.

Related

Автор статьи: Arthur Isaev

Изображение баннера