Groovy allows you to create a methods with optional parameter, but the trailing parameter is only optional, see the below example.
The main method.
The function call mathLog.log(10) takes the base value as 10, that's defined in the method itself but the function call mathLog.log(10,2) takes the 2 as a base value.
The output is
1.0
3.3219280948873626
Note: In Groovy the return statement is optional, because by default it's return the last line output to calling method.
class MathLog { def log(x,base=10) { Math.log(x)/Math.log(base) } }Here the base is optional parameter.
The main method.
MathLog mathLog = new MathLog()
println mathLog.log(10)
println mathLog.log(10,2)
The function call mathLog.log(10) takes the base value as 10, that's defined in the method itself but the function call mathLog.log(10,2) takes the 2 as a base value.
The output is
1.0
3.3219280948873626
Note: In Groovy the return statement is optional, because by default it's return the last line output to calling method.
Comments