Using enhancements to make types compatible with structures

Gosu enhancements are a language feature to add methods and properties to other types even if you do not control the implementation classes for those types. Programming access to enhancements methods and properties are dispatched statically at compile time based on the programming context. For example, if you add the toPublicName method to the type MyClass, every programming context for an instance of MyClass now supports the toPublicName method.

You can use Gosu enhancements to add methods and features to types that make the types compatible with structural types. For example, suppose you want a structural type to work with multiple types that have a toPublicName method that returns a String value. You might create a structure such as:

structure HasPublicName {
  public function toPublicName() : String
}

Suppose a relevant class does not provide the toPublicName method but exposes the appropriate data using other methods or properties. You can add a Gosu enhancement to add the desired property on target types, in this case instances of the com.example.MyClass class:

enhancement AddDisplayNameToString: com.example.MyClass {
  public function toPublicName() : String {
    return this.toString()
  }
}

Any instance of com.example.MyClass has the toPublicName function and is compatible with the structure that requires that method:

uses com.example.MyClass

var s = new MyClass()      // Create a new String

var named : HasPublicName  // Variable declared to a structural type

// Assign a MyClass to the structural type. This code works because of the Gosu enhancement method.
named = s 

See also