Null safe usage
Using property references that might be null in expressions can lead to unexpected results. This topic contains examples and how to handle them.
The examples in this topic use the following data model:
{
"user": {
"name": {
"given": "John",
"family": "Doe"
}
}
String concatenation
- Issue
-
Because
user.name.middle
is null, the expressionuser.name.given + ', ' + user.name.middle + ', ' + user.name.family
returnsJohn, null, Doe
. - Solution to concatenate only non-null values
-
#string.join({user.name.given, user.name.middle, user.name.family}, ', ')
returnsJohn, Doe
. - Issue
-
Because
user.age
is null and the other operand is numeric, the expression3 + user.age
returns an error. - Solution to avoid errors using an Elvis operator to add a default value
-
3 + (user.age ?: '')
returns3
.