Optional Parameters

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 ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.