66. Parameters
We just saw that closures have an in-built it parameter but we can specify a parameter when we declare the closure:
def cls = { name -> println "Hello, $name" }
cls('Jerry')
In the example above I declare the name parameter and this replaces it - in fact, if I called it within the closure I’d get an exception.
The syntax of closures is starting to become evident:
- Start the closure with
{ - List parameters, followed by
-> - Write a set of statements for the closure body
- End the closure with
}
Each parameter is separated using a comma (,):
def cls = { name, pet -> println "Hello, $name. How is your $pet?" }
cls('Jerry', 'cat')
As the closure gets more complicated I like to break it up over a number of lines. I start the closure and declare the parameters on the first line. The body of the closure then follows much the same as a method body and a final line closes off the closure:
def cls = { name, pet ->
println "Hello, $name. How is your $pet?"
}
cls('Barry', 'Lemur')
Closure parameters let me do the same things I can do with method parameters:
- Use data types for parameters
- Provide default values
- Varargs
- Named parameters
Parameter data types:
def cls = { String name, String pet ->
println "Hello, $name. How is your $pet?"
}
cls('Sally', 'Echidna')
Default values:
def cls = { name, pet = 'dog' ->
println "Hello, $name. How is your $pet?"
}
cls('Barry')
Varargs:
def cls = { name, ... pets ->
println "Hello, $name. How are your $pets?"
}
cls('Herman', 'cat', 'dog', 'spider')
Named parameters:
def cls = { grades, name ->
println "This year $name received the following grades: $grades"
}
cls(maths: 'D', science: 'C', art: 'A', 'Albert')
So closures and methods are rather similar - there’s no black magic going on.