Compound types
To implement other features, Gosu supports a special type called a compound type. A compound type combines an optional base class and additional interfaces. Typical usage of compound types occurs only when Gosu automatically creates a variable with a compound type because of type inference. In extremely rare cases, Gosu allows a variable to be declared explicitly with a compound type.
Suppose you use the following code to initialize list values with different types of objects. When used with initializers, the run-time type is always ArrayList<Object, Object>. The compile-time type depends on what you pass to the initializer. Gosu infers the type of the result list to be the least upper bound of the components of the list. If you pass different types of objects, Gosu finds the most specific type that includes all of the items in the list.
If the types implement interfaces, Gosu attempts to preserve commonality of interface support in the list type. This behavior ensures that your list acts as expected with APIs that rely on support for the interface. In some cases, the resulting type is a compound type, which combines:
- Zero classes or one class, which might be
java.lang.Object, if no other common class is found - One or more interfaces
At compile time, the list and its elements use the compound type. You can use the list and its elements with APIs that expect those interfaces or the ancestor element.
For example, the following code creates classes that extend a parent class and implement an interface.
interface HasHello {
function hello()
}
class TestParent {
function unusedMethod() {}
}
class TestA extends TestParent implements HasHello{
function hello() {print("Hi A!")}
}
class TestB extends TestParent implements HasHello{
function hello() {print("Hi B!")}
}
var newList = { new TestA(), new TestB()}
print("Run-time type = " + typeof newList)
This code prints the following line.
Run-time type = java.util.ArrayList<java.lang.Object>
The compile-time type is a combination of:
- The class TestParent, which is the most specific type in common for
TestAandTestB - The interface
HasHello, which bothTestAandTestBimplement
Gosu also creates compound types in the special case of using the delegate keyword with
multiple interfaces.
