Object property access

Property accessor syntax

Gosu retrieves a property’s value by using the period operator. You can chain this expression with additional property accessors. Gosu handles null values in the expression to the left of the period differently from many other languages. Your code uses Gosu behavior to handle null values to avoid null pointer exceptions (NPE).

Syntax

object.PROPERTY_NAME

Examples

Expression

Result

Claim.Contacts.Attorney.Name

Pam Trujillo

Claim.Addresses[0].State

New Mexico

Associative array syntax

For most types other than Gosu arrays, you can use associative array syntax to access the elements, or properties, of an object. With associative array syntax, you access an object property with a String value in square brackets that contains the property name instead of an index number.

The following code uses associative array syntax to get the postal code of a contact.

contact["PostalCode"] 

Use associative array syntax if a property name is unknown at compile but can be determined at run time with input from users. If the property name does not exist at run time, Gosu throws an exception.

Warning: Gosu cannot check associative array syntax at compile time to be certain that a property name is accurate or that the property exists. Be careful whenever you use associate array syntax to catch unexpected run time errors. Use property path expressions, which provide type-safe property access, instead of associative array syntax whenever possible.

Associative arrays on objects in Gosu are similar to instances of the Java map class java.util.Map. Associative array syntax for property access works with most classes, including the Map class and types that do not take array-style index numbers.

You cannot use associative array syntax with String objects in Gosu. A String object behaves like an ordered list of characters and requires array index notation to access its individual character elements.

Syntax

object[PROPERTY_NAME_STRING]

Examples

The following code demonstrates single associative array syntax to get the StreetAddress property on a Person object. At run time, the code is equivalent to the property path expression person.StreetAddress. The code might evaluate to 123 Main Street.

person["StreetAddress"] 

The following code demonstrates double associative array syntax to get the City property on the Address object that is a property of a Person object. At run time, the code is equivalent to the property path expression person.Address.City. The code might evaluate to Birmingham.

person["Address"]["City"] 

The following code uses single associative array syntax to set the City property on an Address object.

newAddress["City"] = "Birmingham"

See also