Created
April 20, 2015 12:15
-
-
Save JakobOvrum/7e3a7bc130ab7db28de3 to your computer and use it in GitHub Desktop.
Approximation of C#'s Null Propagation Operator in D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
{ | |
string name; | |
this(string name) | |
{ | |
this.name = name; | |
} | |
} | |
class Bar | |
{ | |
Foo foo; | |
this(Foo foo) | |
{ | |
this.foo = foo; | |
} | |
} | |
class Baz | |
{ | |
Bar bar; | |
this(Bar bar) | |
{ | |
this.bar = bar; | |
} | |
} | |
template getOrNull(string op, ops...) | |
{ | |
auto getOrNull(T)(T obj) | |
{ | |
auto result = __traits(getMember, obj, op); | |
static if(ops.length) | |
{ | |
return result is null? null : .getOrNull!ops(result); | |
} | |
else | |
return result; | |
} | |
} | |
unittest | |
{ | |
auto threeDeep = new Baz(new Bar(new Foo("foobar"))); | |
assert(threeDeep.getOrNull!("bar", "foo", "name") == "foobar"); | |
auto nullCases = [ | |
new Baz(new Bar(new Foo(null))), | |
new Baz(new Bar(null)), | |
new Baz(null) | |
]; | |
foreach(nullCase; nullCases) | |
assert(nullCase.getOrNull!("bar", "foo", "name") is null); | |
assert(nullCases[0].getOrNull!("bar", "foo") !is null); | |
assert(nullCases[1].getOrNull!("bar") !is null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment