1

I am trying to pass multiple string as parameter to the function

Function:

void addColumn(java.lang.String... headers)

Description

Add a row of column headers to this grid. This should be called once per dimension on the column, and the length of headers from each dimension should match.

Example call from Groovy that adds Jan, Feb, Mar from FY16 and FY17:

builder.addColumn('2016', '2016', '2016', '2017', '2017', '2017') 
builder.addColumn('Jan', 'Feb', 'Mar', Jan', 'Feb', 'Mar')

So If I pass the parameter like in the above example it works fine.. I couldn't figure out the way to pass it dynamically in groovy??

2 Answers 2

5

You can always pass an array of Strings in this case. Your method

void addColumn(java.lang.String... headers)

uses varargs and it means that you can call this method as it was

void addColumn(java.lang.String[] headers)

Varargs is useful in some cases, because it accepts single parameter as well as n-number of parameters with the same type.

If you want to call this method in Groovy you can do it by passing a list cast to String[], e.g.

def addColumn(String... args) {
    args.each { println "Adding column ${it}..."}
}

println 'Ex 1:'
addColumn('Jan', 'Feb', 'Mar', 'Apr')

println 'Ex 2:'
addColumn(['Jan', 'Feb', 'Mar', 'Apr'] as String[])

Running this script will print to the output:

Ex 1:
Adding column Jan...
Adding column Feb...
Adding column Mar...
Adding column Apr...
Ex 2:
Adding column Jan...
Adding column Feb...
Adding column Mar...
Adding column Apr...

I hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use the splat operator:

def headers = ['Jan', 'Feb', 'Mar', 'Jan', 'Feb', 'Mar']

addColumn(*headers)

which will unroll the collection as varags in this case.

6 Comments

Thanks for response.. I tried the code but it gave me this error..[Static type checking] - The spread operator cannot be used as argument of method or closure calls with static type checking because the number of arguments cannot be determined at compile time
Are you using @CompileStatic on your code? If so, it won't work with that you'd need to remove the annotation. If you can't remove it, then I am not sure how to do what you ask.
You could also mark the specific method that this code is in with the SKIP version of the annotation to make it non-static.
I am not aware of @compilestatic. This function is provided by the Oracle tool and we are just calling this function. As I mention if I hardcode addColumn(Jan,Feb) it works but I want to pass the parameters dynamically.. not sure how to get this work :(
If this tool is forcing static compilation, then not sure what you can do.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.