Type inference and list initialization
Because of Gosu type inference, you can use a very concise syntax to create and initialize a list.
var s3 = {"a", "ab", "abc"}The compile-time type of the
list is java.util.ArrayList<String>.
The run-time type is different, java.util.ArrayList<Object>.
Gosu infers the type of the result list as 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
See also
