Reputation: 3994
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:
To top this, is there a way to chain such get operations for deeply nested attributes?
Upvotes: 10
Views: 3345
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
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