On Tuesday, 13 March 2018 at 13:13:07 UTC, rumbu wrote:
On Tuesday, 13 March 2018 at 12:23:06 UTC, Ozan Süel wrote:

I have a construction like the following

if (source) {
  if (source.pool) {
    if (source.pool.repository) {
      if (source.pool.repository.directory) {
        if (source.pool.repository.directory.users) {
          // do something

Any chance to simplify this nested ifs?
I know some languages has a way like.

if (source?pool?repository?directory?users) // do something

Similar ways in D?

Thanks and Regards, Ozan

You need the null conditional operator which is not available in D.

A library solution can be found there: https://forum.dlang.org/post/mailman.2562.1403196857.2907.digitalmar...@puremagic.com


This library may help as well: https://code.dlang.org/packages/optional

It will handle safe dispatching of reference types and pointer types and give you back the actual return result as well wrapped up in an optional value.

class C0 {
    C1 f() { return new C1(); }
    class C1 {
        C2 f() { return new C2(); }
        class C2 {
            int f() { return 0; }

auto res1 = some!C0(null).dispatch.f.f.f; // all no ops
auto res2 = some!C0(new C0()).dispatch.f.f.f // calls all fs

assert(res1 == none);
assert(res2 == some(0));

Reply via email to