July 2013
Intermediate to advanced
370 pages
8h 27m
English
In Groovy we can make method and constructor parameters optional. In fact, we can make as many parameters optional as we like, but they have to be trailing. We can use this in evolutionary design to add new parameters to existing methods.
To define an optional parameter, simply give it a value in the parameter list.
Here’s an example of a
log
function with optional
base parameter. If we don’t provide that argument, Groovy assumes a value of 10:
| GroovyForJavaEyes/OptionalParameters.groovy | |
| | def log(x, base=10) { |
| | Math.log(x) / Math.log(base) |
| | } |
| | |
| | println log(1024) |
| | println log(1024, 10) |
| | println log(1024, 2) |
Groovy fills the missing argument with the optional value, as we can see in the output:
| | 3.0102999566398116 ... |
Read now
Unlock full access