Null-safe default operator
Sometimes you need to return a different value
based on whether an expression evaluates to null. The Gosu operator ?: results in the value of the
expression to the left of the operator if that value is non-null, avoiding
evaluation of expression to the right. If the value of the expression
to the left of the operator is null,
Gosu evaluates the expression to the right and returns that result.
For example, suppose there is a variable
str of type String. At run time, the value
contains either a String
or null. Perhaps you want
to pass the input to a display routine. However, if the value of str is null, you want to use a default
value rather than null.
Use the ?: operator as
follows:
var result = str ?: "(empty)" // Return str, but if the value is null return a default string
You can chain the null-safe default operator to get the first non-null value in a set of items. If every
value in the chain is null, the result of the chain is null. For example, the
following code gets the first day of the week that has an assigned task or returns null if no day
has a task:
var firstTask = dayTask[0] ?: dayTask[1] ?: dayTask[2] ?: dayTask[3] ?: dayTask[4]