Groovy : What is Safe Navigation operator or Null check Operator

Safe navigation operator

The safe navigation Operator is used to avoid null pointer exceptions. Many a times you come across the need to access the value of an object if it is not null.

Syntax for the Safe Navigation Operator is

<object>?.<property>

Here the could be any object and could be any property of the object.

Let's have a look at the below example,

class User {
  String name;
}

User u  = new User(name : "ekiras")

if(u != null)
  println u.name  // prints ekiras

In the above code we have to write the if block to check if the user object is null or not. So, with the Safe navigation operator we do not need to write the if-else blocks.

We can rewrite the above code as shown below

class User {
  String name;
}

User u  = new User(name : "ekiras")

println u?.name // prints ekiras

No comments:

Powered by Blogger.