Aakash Verma
Aakash Verma

Reputation: 3994

Is there an equivalent of Javascript's optional chaining in Java?

String answer = question1?.question2?.answer

Is there a way (preferably in-built) to get the property of an object where both the following scenarios are covered:

  1. If the object is null, return a null value for the attribute.
  2. Returns null for an attribute if it doesn't exist in the object.

To top this, is there a way to chain such get operations for deeply nested attributes?

Upvotes: 10

Views: 3345

Answers (2)

Traian GEICU
Traian GEICU

Reputation: 1786

it's possible to obtain "similar" behavior(chain) but just with custom code ( not being something inbuild)

public class TestChain 
{
    public static void main(String args[]) 
    {
        TestChain tc = new TestChain();
        Person p = tc. new Person();
        p.setName("pName").getMsg().setAge(10).getMsg();
    }
    
    class Person
    {
        String name;
        int age;
        public Person setName(String name)
        {
            this.name = name;
            return this;
        }
        
        public Person setAge(int age)
        {
            this.age = age;
            return this;
        }
        
        public Person getMsg()
        {
            System.out.println(this);
            return this;
        }
        public String toString()
        {
            return "name="+name+",age="+age;
        }
        
    }
}

Output:

name=pName,age=0
name=pName,age=10

Basically methods to be chained need to return current instance.

Upvotes: -5

Dale
Dale

Reputation: 1628

Java doesn't however Groovy does. When writing Groovy you can mix java right in with it. In Groovy you can do println company?.address?.street?.name

Upvotes: 1

Related Questions