Skip to content

Null is checked when you compile

In Novis a variable of type User is always a User. A value that may be missing has a type that starts with ?, such as ?User:

<?nvs
// This program looks up a user by id. The user may not exist.
class User
{
public string $name;
public function constructor(string $name)
{
$this->name = $name;
}
}
class Users
{
// `?User` is a `User` or `null`. A plain `User` is never `null`.
public static function find(int $id): ?User
{
return $id == 1 ? new User('Ada') : null;
}
}
// `?->` reads the property only when the object is not `null`.
// `??` gives the value on the right when the left side is `null`.
echo Users::find(1)?->name ?? 'nobody', "\n";
echo Users::find(2)?->name ?? 'nobody', "\n";
Output
Ada
nobody

?-> reads a property only when the object is not null. ?? gives a default value.

If you use -> on a value that may be null, the program does not compile:

error[E0459]: `null|User` may be `null`, so `->` cannot reach a member of it
--> users.nvs:16:6
|
16 | echo Users::find(2)->name, "\n";
| ^^^^^^^^^^^^^^ this receiver is nullable

The compiler shows the missing check. You fix it before the program runs on a server.

Read more in Syntax: nullable types and Syntax: null coalescing.