Safe Navigation Operator (?.) is used to get rid off
NullPointerException.
For example, below script defines an Employee class and a
function that prints employee details.
HelloWorld.groovy
class Employee{ String firstName String lastName } Employee emp = new Employee() printEmployeeDetails(emp) void printEmployeeDetails(Employee employee){ String firstName, lastName if(employee.firstName == null){ firstName = null }else{ firstName = employee.firstName } if(employee.lastName == null){ lastName = null }else{ lastName = employee.lastName } println "[${firstName}, ${lastName}]" }
Output
[null, null]
if(employee.firstName == null){
firstName =
null
}else{
firstName =
employee.firstName
}
We can rewrite the above snippet using elvis opeator like
below. If firstName of the employee is null, then elvis operator return null,
else it return the actual value.
String firstName = employee?.firstName
Find the below working application.
HelloWorld.groovy
class Employee{ String firstName String lastName } Employee emp = new Employee() printEmployeeDetails(emp) void printEmployeeDetails(Employee employee){ String firstName = employee?.firstName String lastName = employee ?.lastName println "[${firstName}, ${lastName}]" }
Output
[null, null]
No comments:
Post a Comment