Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Safe Navigation Operator



safe navigation operator ?. is a powerful tool in Groovy to avoid null pointer exceptions while accessing properties or methods of potential null object. It provides an elegant and concise way to navigate through object's nested properties or methods.

Syntax - Safe Navigation Operator

Object?.property
Object?.method()
Object?.nested-property?.another-nested-property

Working of Safe Navigation Operator

  • When a safe navigation(?.) operator is used instead of normal dot(.) operator, Groovy checks if object on the left side is null.

  • In case object is not null then safe navigation(?.) operator works same as normal dot(.) operator.

  • If object is null then safe navigation(?.) operator instead of throwing a null pointer exception returns null gracefully and skip rest of the nested chain.

Example - Accessing a potential null property

Example.groovy

class Address {
   String city
}

class User {
   Address address
   String name
}

def user = new User(name: "Julie")
def address = user.address
def city = user?.address?.city

println "Address: ${address}"
// prints null instead of null pointer as address is null
println "City: ${city}"

Output

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

Address: null
City: null

Example - Accessing a potential null method

Example.groovy

class Address {
   String city
}

class User {
   Address address
   String name
}

def user = null
def name = user?.getName()
println "Name: ${name}"

Output

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

Name: null

Example - Chaining safe navigation Operators

Example.groovy

class Address {
   String city
   String street
}

class User {
   Address address
   String name
}

def street = user?.address?.street?.toUpperCase()

// street is null if any of user, address or street is null
println "Street: ${street}"

Output

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

Street: null

Example - Chaining safe navigation Operators

Example.groovy

class Address {
   String city
   String street
}

class User {
   Address address
   String name
}

def user = null
def street = user?.address?.street?.toUpperCase()

// street is null if any of user, address or street is null
println "Street: ${street}"

Output

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

Street: null

Example - Integration with Elvis Operator

Example.groovy

class Address {
   String city
   String street
}

class User {
   Address address
   String name
}

def user = null

def city = user?.address?.city ?: "Unknown City"
println "City: ${city}"

def nameLength = user?.name?.length() ?: 0
println "Length of Name: ${nameLength}" 

Output

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

City: Unknown City
Length of Name: 0
Advertisements