Mascara Try it Download Buy About Documentation Blog

Nullability

Nullability is the question if a type allows the value null or not. The compiler tracks nullability, which eliminates a host of errors.

A variable of a non-nullable type has to be assigned an initial value.

For example, Date is nullable, while int is non-nullable. So:

var a : Date; // this is OK
var b : Date = null; // this is also OK
var c : int; // ERROR, has to be assigned a value
var d : int = null; // also ERROR, int cannot be null
var e : int = 7; // this is OK
Only the built-in types int, float, boolean and string are non-nullable. All other types (including user defined classes and types), are nullable by default.

It is however possible to make a type non-nullable by prefixing with a "!".:

var x : !Date = new Date(); // x cannot be null!
x = null; // ERROR

And, correspondingly, a non-nullable type can be declared nullable by prefixing with a ?:

var x : ?int = 7; 

Caveat with inner functions

It is not allowed to declare a variable as non-nullable, if that variable is read from an inner function. Example:

var x : int = 1;  //WARNING: x cannot be non-nullable
function f(){ var b = x; } 

The reason is that the function could be called before the variable is initialized with a value. Since the compiler cannot guarantee that the variable has been assigned at the time it is read, it cannot guarantee that it is not-nullable. In this case it has to be declared as ?int, i.e. nullable int.