Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Elvis Operator



elvis operator is a shorthand for ternary operator. It simplifies the null checks and is used to provide default values. elvis name comes because of resemblance with Elvis Presley's iconic hairstyle with ?:.

Syntax - Elvis Operator

variable = expression ?: defaultValue

It is equivalent to more elaborate terniary operator.

variable = expression ? expression : defaultValue

Characteristics of Elvis Operator

  • Falsey Value − Elvis operator checks for truth value instead of just null value. Left operand is considered false if it is null, false, 0, an empty collection or an empty string. When left operand is falsey then default value is returned as right operand.

  • Concise Syntax − As elvis operator handles multiple falsey values seemlessly, it reduces the verbosity of the code making it concise and clear.

  • Short Circuiting − Right operand is evaluated only in case when left operands turns falsey.

Example - Getting a Default Name

In this example, we're checking if name is falsey then use of elvis operator returns Guest as default name.

Example.groovy

username = ''
def name = username ?: "Guest"
println "Hello, ${name}"

Output

When we run the above program, we will get the following result.

Hello, Guest

Example - Setting a Default Price

In this example, we're checking if price is 0 then we're setting 9.9.

Example.groovy

price = null
def priceOfProduct = price ?: 9.9
println "The price is: ${priceOfProduct}"

Output

When we run the above program, we will get the following result.

The price is: 9.9

Example - Chaining Elvis Operator

In this example, we're chaining elvis operator in case of multiple fallbacks.

Example.groovy

phone = null
email = ''
def contactInfo = phone ?: email ?: "Contact info is not available"
println "Contact: ${contactInfo}"

Output

When we run the above program, we will get the following result.

Contact: Contact info is not available
Advertisements