1

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?

Fenton
  • 241,084
  • 71
  • 387
  • 401

1 Answers1

1

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.

Fenton
  • 241,084
  • 71
  • 387
  • 401