Delphi's New Feature Desired: Nullable Types and Null Propagation

Delphi's New Feature Desired: Nullable Types and Null Propagation

Nullable types are a common feature on the .NET Runtime, but Delphi does not supply a language integration to we have fun with it.

Nullable types should have the following characteristics (borrowed from .NET):
  - Nullable types represent value-type variables that can be assigned the value of nil. You cannot create a nullable type based on a reference type. (Reference types already support the nil value.)
  - Assign a value to a nullable type just as you would for an ordinary value type. A nullable type can also be assigned the value nil.
  - Use the GetValueOrDefault(const obj: TNullable) global function to return either the assigned value, or the default value for the underlying type if the value is nil.
  - Use the HasValue and Value global functions to test for nil and retrieve the value.
  - The HasValue global function returns true if the variable contains a value, or false if it is nil.
  - The Value global function returns a value if one is assigned. Otherwise, a exception is thrown.
  - You can also use the = and <> operators with a nullable type.
  - Nested nullable types are not allowed.

Proposed syntax:
"type
  TNullable = nullable of T;

var
  y: TNullable;"

In Delphi, the "." operator is used to call members on a class or object, such as

"var x := y.SomeProperty;"

This "dereferences" the object contained in "y", calls the property getter and returns its value. If "y" happens to be unassigned (i.e. "nil"), an exception is thrown.

Delphi needs a new operator for play well with unassigned objects. The proposed operator is ":" and it works in much the same way as ".", but instead of throwing an exception on an unassigned object, the result will simply be nil. Look at the example below:

"var
  [..]
  Length: TNullable;
begin
  [..]
  Length := SomeString:Length; 
end;"

The variable "Length" will be of type "nullable of Integer" and it will contain nil, if SomeString itself is nil.

An more complex example is showed below:
"var
  [..]
  Length: TNullable;
begin
  [..]
  Length := MyForm:OkButton:Caption:Length; 
end;"

Will run without error, and return nil if any of the objects in the chain are nil — the form, the button or its caption.

The problem of the features is the language syntax, I fear that the syntax becomes more complex to fit these features. The proposed syntax is not fixed, it may be other than this. It is just a suggestion, the most import things are in the essence of the proposed features.

I am not a Embarcadero guy :D

Comments