Dynamic types and expando objects

Gosu supports dynamic language features that permit coding styles similar to non-statically typed languages. The dynamic.Dynamic type allows dynamic assignment as well as dynamic dispatch of property access and method invocation. Gosu also provides support for expando objects, which simplify dynamic property and method access for typical code contexts.

Overview of dynamic language features

Gosu is a statically typed language employing a nominal type system. A nominal type system is one in which type assignability is based on declared type names, type ancestry, and declared interfaces. Because Gosu is statically typed, in general programming, access to properties is dependent on the property definitions of the declared class. In typical code, these restrictions encourage coding styles that catch most types of programming errors at compile time, and support refactoring code safely.

In rare cases, dynamic coding styles can be useful. The Gosu type system supports two features that expand support for dynamic type access:

  • Dynamic type declaration – Declare a variable or function parameter as the type dynamic.Dynamic to allow assigning any reference type. This type declaration enables dynamic dispatch of property and method invocation by the name of the property or method.
  • Expando object support – Expando objects are objects that use the dynamic declaration and store properties as key-value mappings in a javax.script.Bindings object. That class extends the java.util.Map class.

You can use these features to use coding styles that are common in languages that are not statically typed.

Warning: Use dynamic language features judiciously because misuse can hide errors that the Gosu editor cannot catch at compile type. For example, if you misspell a property or method name, there is no compiler error but run time errors can occur.

Note that these two features are separate from structural types. Structural types are similar to interfaces but can be used with objects with no shared ancestry or interfaces.

See also