Skip to content

4. Values that may be missing

Some values are not always there. A task may have a note or not, and a search may find no task. In Novis, the type says this. ?Task is a Task or null:

<?nvs
// This program looks up a task by its title. The task may not exist.
class Task
{
public string $title;
public ?string $note = null;
public function constructor(string $title)
{
$this->title = $title;
}
}
class Tasks
{
// `?Task` is a `Task` or `null`. This method returns `null` when no task has the title.
public static function find(array<Task> $tasks, string $title): ?Task
{
foreach ($tasks as Task $task) {
if ($task->title == $title) {
return $task;
}
}
return null;
}
}
array<Task> $tasks = [new Task('Buy milk'), new Task('Call Ada')];
$tasks[1]->note = 'after 5 pm';
// `?->` reads the property only when the object is not `null`.
// `??` gives the value on the right when the left side is `null`.
echo Tasks::find($tasks, 'Call Ada')?->note ?? 'no note', "\n";
echo Tasks::find($tasks, 'Buy milk')?->note ?? 'no note', "\n";
echo Tasks::find($tasks, 'Fly to Mars')?->note ?? 'no note', "\n";
Output
after 5 pm
no note
no note

?string is a string or null. ?Task is a Task or null. A variable of type string can never be null, so you only check the values whose type starts with ?.

?-> reads a property only when the object is not null. Otherwise the result is null. ?? then gives the value on its right side.

If you leave out the ? in ?->, the program does not compile. The compiler checks that find may return null.

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

Next: step 5, errors.