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.middleis null, the expressionuser.name.given + ', ' + user.name.middle + ', ' + user.name.familyreturnsJohn, 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.ageis null and the other operand is numeric, the expression3 + user.agereturns an error. - Solution to avoid errors using an Elvis operator to add a default value
-
3 + (user.age ?: '')returns3.