Skip to content

Every conversion is checked

Some languages convert "12abc" to the number 12 without a warning. In Novis you convert a value with as, and the conversion is checked:

<?nvs
// This program converts text to numbers. Each conversion is checked.
string $quantity = '12';
string $typo = '12abc';
// `as int` converts the text. "12" is a whole number, so this prints `13`.
echo ($quantity as int) + 1, "\n";
// `as ?int` gives `null` when the text is not a whole number.
echo ($typo as ?int) ?? 'not a number', "\n";
// `as int` throws an error when the conversion is not possible.
try {
echo $typo as int, "\n";
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
13
not a number
cannot convert a `string` of 5 bytes to `int`

as int gives the number when the text is a whole number. Otherwise it throws an error.

as ?int gives null when the conversion is not possible. Use it with ?? to give a default value.

Novis converts a value without as only when nothing can be lost. An int fits into a float, for example.

Read more in Syntax: converting with as.