I want to use optional object like Java.
I want to use it like this:
car.engie.plug
I expect that it return null if car
or engine
is null and not throw an exception.
How can I do it?
I want to use optional object like Java.
I want to use it like this:
car.engie.plug
I expect that it return null if car
or engine
is null and not throw an exception.
How can I do it?
There is no language feature for this, but you can use simple existing language features to achieve the same result...
if (car && car.engine && car.engine.plug) {
return car.engine.plug;
} else {
return null;
}
You could also use the null object pattern to ensure you never have to handle this situation.