Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Default Value for variables

In Groovy we can assign default values to parameters in a method, like this:

def say(msg = 'Hello', name = 'world') {
    "$msg $name!"
}

However, what's the simplest way to assign default values for variable assignments, when they are not from the method parameters, like environment variables or JMeter variables, as in Can I override User Variables in Test Fragment?

Is this the only way?

def mySession = System.getenv("SESSIONNAME") ? System.getenv("SESSIONNAME") : "Session Default"

Is there any other ways, like in NodeJS syntax:

def mySession = System.getenv("SESSIONNAME") || "Dfault"?

like image 956
xpt Avatar asked Oct 18 '25 15:10

xpt


1 Answers

You can use the Elvis operator ?: that uses the provided value if it satisfies Groovy truth.

def mySession = System.getenv("SESSIONNAME") ?: "Dfault"

It will work unexpectedly and use the default value if the provided value exists and is e.g. false or [], but for all non-empty/non-false values it will work.

https://groovy-lang.org/operators.html#_elvis_operator

like image 129
Onno Rouast Avatar answered Oct 21 '25 23:10

Onno Rouast