Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy method with optional parameters

I would like to write a wrapper method for a webservice, the service accepts 2 mandatory and 3 optional parameters.

To have a shorter example, I would like to get the following code working

def myMethod(pParm1='1', pParm2='2') {     println "${pParm1}${pParm2}" }  myMethod(); myMethod('a') myMethod(pParm2:'a') // doesn't work as expected myMethod('b','c') 

The output is:

12 a2 [pParm2:a]2 a2 bc 

What I would like to achieve is to give one parameter and get 1a as the result. Is this possible (in the laziest way)?

like image 202
Chris Avatar asked Aug 09 '13 14:08

Chris


People also ask

Can we use optional as method parameter?

Java static code analysis: "Optional" should not be used for parameters.

How do you call a method in Groovy?

In Groovy we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

How do I use def in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language. Here, firstName will be a String, and listOfCountries will be an ArrayList. Here, multiply can return any type of object, depending on the parameters we pass to it.


2 Answers

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){     println "${pParm1}${pParm2}" } 

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {     println "$pParm1$pParm2" }  Object myMethod( pParm1 ) {     this.myMethod( pParm1, '2' ) }  Object myMethod() {     this.myMethod( '1', '2' ) } 

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){     println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}" }  myMethod( 'a', 'b' )                // prints 'a b 1 2' myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2' myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd' 

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

like image 114
tim_yates Avatar answered Oct 07 '22 08:10

tim_yates


You can use arguments with default values.

def someMethod(def mandatory,def optional=null){} 

if argument "optional" not exist, it turns to "null".

like image 42
Alex Avatar answered Oct 07 '22 09:10

Alex