Skip to content

Add null-conditional member access.

philippejer requested to merge philippejer/vala:wip/null-conditional into master

This is an implementation of the "null-conditional" operator of C# (.?), which is the companion of the "null coalescing" operator (??).

I'm not very familiar with the compiler internals but I took my inspiration from the implementation of the null coalescing operator, as it is fairly similar (although it turned out a bit more complex to implement).

It supports both the common null-conditional member access form, but also the method call form (which is more complex as it needs to handle void methods specifically).

It probably needs some improvements and unit tests but since it is quite a non-trivial addition to the language, I wanted to test the waters first :)

There may be some technical or more principled objections to this operator? (it can certainly make the code less readable if abused)

If this is accepted, I'll gladly update the Wiki and reference manual of course.

Note that it supports compilation in non-null mode (the inner expression is cast as non null if it passes the non-null check).

Typical usage:

public class AAA {
  public string s { get; set; }

  public void print() {
    message(s);
  }
}

void main() {
  AAA? a = new AAA() { s = "hello" };
  a?.print(); // prints "hello"
  a = null;
  a?.print(); // does nothing
  //  string s = a.s; // does not compile in non-null mode
  //  string s = a?.s; // does not compile in non-null mode
  string s = a?.s ?? "null"; // compiles in non-null mode
  message(@"the string is '$(s)'", s); // prints "the string is 'null'"
}

Fixes #522 (closed)

Edited by Rico Tzschichholz

Merge request reports