Nullable Types

Nullable types enable internal JS++ types to accept null values.

1
2
3
4
int x = 1;
// x = null; // ERROR
int? y = 1;
y = null;    // OK

Operators

JS++ provides three operators for working with nullable types: ?? (safe default operator), ?. (safe navigation operator), and ?= (safe assignment operator).

Safe Default Operator

The safe default operator can be used for providing an alternative value if a null value is encountered:

1
2
int? x = null;
int? y = x ?? 5; // y == 5
Safe Navigation Operator

The safe navigation operator is similar to the . operator except it only looks up class members if the object is not null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import System;
 
class Foo
{
    Foo? maybe() {
        if (Math.random() > 0.5) {
            return this;
        }
        else {
            return null;
        }
    }
 
    void log() {
        Console.log("Something happened.");
    }
}
 
auto foo = new Foo();
foo.maybe()?.log();

In the above code, maybe can return either an instance of the class or null. By using the safe navigation operator (?.), the log method will only be called if the class instance was returned by maybe.

Safe Assignment Operator

The safe assignment operator can be used to assign a different value if a null value is present:

1
2
3
4
5
6
import System;
 
int? x = null;
Console.log(x); // null
x ?= 5;
Console.log(x); // 5

Casting

Nullable types can be stripped away via casting:

1
2
3
4
class Foo {}
 
Foo? foo = new Foo();
Foo bar = (Foo) foo;

Casting can throw a CastException. Therefore, it is preferred to use the nullable operators instead. If casting is absolutely necessary, it is preferred to perform a check first:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import System;
 
class Foo {}
 
Foo? foo;
if (Math.random() > 0.5) {
    foo = new Foo();
}
else {
    foo = null;
}
 
if (foo != null) { // this check makes sure the cast is safe
    Foo bar = (Foo) foo;
}

Unlike casting from other types, casting from nullable or existent types will only strip the nullable or existent type. It will not simultaneously allow downcasting. If you desire to downcast, you need to downcast separately.

See Also

Share

HTML | BBCode | Direct Link