Michal Kordas
Michal Kordas

Reputation: 10925

Optional parameter in Groovy Script

I have a script that simply does

// TODO: assign default value if not defined
println optionalParameter

When I invoke it using:

new GroovyShell(new Binding([optionalParameter: 'text'])).evaluate(script)

it works fine. But if I run it without a parameter like below:

new GroovyShell().evaluate(script)

it fails with MissingPropertyException.

How can I assign default value for optionalParameter so that I don't get MissingPropertyException?

Upvotes: 0

Views: 1009

Answers (1)

Michal Kordas
Michal Kordas

Reputation: 10925

Adding this code to script works for me:

String value
if (binding.hasVariable('optionalParameter')) {
    value = binding.getVariable('optionalParameter')
} else {
    value = 'defaultValue'
}
println value

Upvotes: 1

Related Questions