Null-safe indexing for arrays, lists, and maps
For objects such as arrays and lists, you can access items by index number, such as
myArray[2]. Similarly, with maps (java.util.Map
objects), you can pass the key value to obtain the value. For example with a
Map<String, Integer>, you could use the expression
myMap["myvalue"]. The challenge with indexes is that if the object
at run time has the value null, code like this throws a null pointer
exception.
Gosu provides an alternative version of
the indexing operator that is null-safe. Instead of typing just the indexing
subexpression, such as [2],
after an object, prefix the expression with a question mark character.
For example:
var v = myArray?[2]If the value to the left of
the question mark is null,
the entire expression for the operator returns null. If the left-hand-operand
is not null, Gosu evaluates
the index subexpression and indexes the array, list, or map. Finally,
Gosu returns the result, just as for the typical use of the brackets
for indexing lists, arrays, and maps.
Null-safe indexing does not protect against array-index out-of-bounds exceptions. If the
array is non-null, but the index is greater than or equal to the size of the array, Gosu
throws an out-of-bounds exception at run time. Any value of the index causes this
exception if the array is empty rather than null. To test for an empty
array, use the HasElements property.
