Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 307
Aakash Verma Avatar asked Apr 13 '26 04:04

Aakash Verma


1 Answers

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

like image 149
Dale Avatar answered Apr 14 '26 19:04

Dale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!