The Expando class

Gosu provides a default implementation of the IExpando interface called gw.lang.reflect.Expando. This default implementation delegates to a java.util.HashMap for data storage.

The property name is always a String value, the value is an Object. If you get an uninitialized property, the value is null.

For any methods, the value must be a Gosu block. If you try to call a method that does not exist, the method returns the special value IPlaceholder.UNHANDLED.

The following example creates an Expando instance in a variable declared to type Dynamic.

uses gw.lang.reflect.Expando
uses dynamic.Dynamic

// Create new Expando object in a Dynamic variable
var villain : Dynamic = new Expando()

// Set dynamic properties and methods, which are stored internally in a java.util.HashMap
villain.Health = 10
villain.punch = \-> { if ( villain.Health > 0 ) villain.Health-- }
villain.isDead = \-> villain.Health <= 0

// Use the Expando object with a natural, readable syntax:
print("Health = " + villain.Health)

while ( !villain.isDead() ) {
  villain.punch()
  print("After punch, health = " + villain.Health)
}

print("Health = " + villain.Health)

This example prints:

Health = 10
After punch, health = 9
After punch, health = 8
After punch, health = 7
After punch, health = 6
After punch, health = 5
After punch, health = 4
After punch, health = 3
After punch, health = 2
After punch, health = 1
After punch, health = 0
Health = 0

See also