Null
Overview
In THT, the value null represents a couple of different things:
- A placeholder for an object that needs to be initialized.
- A value that is “unknown” or “not found”.
The null Keyword
You can define or check for the existence of null by using the null keyword.
$val = null
if $val == null {
// ...
}
The pending Keyword
The pending keyword is an alias for null.
This clearly communicates that it’s a temporary placeholder that will be initialized with an object soon after.
$task = {
name: ''
dueDate: pending
}
// ...
$task.dueDate = Date.create('+1 week')
0 for numbers, [] for lists, etc.) instead of null or pending.Empty Return Values
Functions return null when there is no explicit return value.
doSomething()
//= null
fun doSomething() {
print('Did Something')
}
Missing Map Keys
Maps return null when you access a key that does not exist, using bracket [...] notation.
$map = { a: 123 }
$map['z']
//= null
Null Operators
Nullval ??: and Nullset ??=
These are like the Orval ||: and Orset ||= operators.
However, they only evaluate the right-hand side if the left-hand value is null.
This can be used to initialize values without overwriting an empty value (e.g. zero, empty string, etc.) that is actually valid.
$player = { name: 'Tai' }
$player['team'] ??= 'none'
//= { name: 'Tai', team: 'none' }
$player['name'] ??= 'guest'
//= { name: 'Tai', team: 'none' }
$score = $player['score'] ??: 0
//= 0
Nulladd ??+=
The Nulladd operator ??+= will default to 0 if the left-hand value is null.
It then applies the add-assign += operator to the value.
This is a useful shortcut for tracking counts in a map.
$numCardsBySuit = {
clubs: 1
}
$numCardsBySuit['clubs'] ??+= 1
$numCardsBySuit['hearts'] ??+= 1
//= { hearts: 1, clubs: 2 }
Nulldot ?.
You can use the Nulldot ?. operator in place of a normal dot . to safely access values that might be null.
If the left-hand value is null, the result will be null without triggering an error.
$map = {}
$a = $map['missingKey'].toUpperCase()
//= (error)
$a = $map['missingKey']?.toUpperCase()
^
//= null (no error)
This can also be combined with the self-assign shortcut.
For example:
$map['missingKey'] = ?.toUpperCase()
Nullable Arguments
In THT, function arguments are non-nullable by default, which means that passing null as an argument to any function will trigger an error.
However, you can make an argument nullable by appending OrNull to the variable name.
fun getProfile($userOrNull) {
$user = $userOrNull ??: getCurrentUser()
// ...
}
Returning Null
If you need to a way to return a value that represents a fail state, we recommend returning a Result object instead of null.