Home > OS >  Groovy Default Value for variables
Groovy Default Value for variables

Time:09-03

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"?

CodePudding user response:

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

  • Related