Handling null values in logical expressions
If your data can provide null values, you need to be aware of how Gosu handles
these values in logical expressions. Using the null-safe operators can propagate
null values from their original sources into other objects and variables in
your code.
-
In an equality test, Gosu returns
trueif both sides of the operator arenullandfalseotherwise. -
In a Boolean expression that uses the
and,or, ornotoperators, Gosu treatsnullas a value offalse.
Be particularly aware of the possibility of null values in code that uses the
and, or, or not operators. If you use
null-safe method operators in logical expressions, your code can produce unexpected results:
var nullStr : String // A string that contains the null value
// Test whether the string is empty
if (nullStr?.isEmpty()) {
print("Empty string") // This message does not appear even though there is nothing in the string.
// Code here to put a value into an empty string does not execute for the null string.
}
// Test whether the string is not empty
if (!nullStr?.isEmpty()) {
print("Got here!") // This message does appear, but the string has no contents.
// If you put code here to use the string value, you risk a null-pointer exception.
}
See also
