Introduction
Static type information in Java provides strong protection against certain kinds of runtime error. As it stands, the static type information required is often unwieldy and repetitive. Type Inference is a well-known technique for inferring the static type of a variable based on its actual usage. Type inference gives the benefits of strong typing, whilst alleviating some of the burdens found with traditional static typing. We consider the restricted local type inference problem, where fields and parameter/return types are given, and the types of local variables are inferred. Several existing languages, most notably Scala, C#3.0 and OCaml, employ type inference. Our approach represents a departure from such systems as we allow variables to have different types at different program points within a method.
Mocha is a language extension to Java which supports local type inference that was developed by Chris Male as part of his MSc thesis here at SMSCS. Consider the following simple method written in Mocha:
Listf(String x) { var y; if(...) { y = new ArrayList (); } else { y = new LinkedList (); } y.add(...) ... return y; }
Here variable y is declared var, indicating its type should be inferred. In fact, y has different inferred types at different points --- ArrayList<String> on the true branch, LinkedList<String> on the false branch and AbstractList<String> after the conditional (which is the nearest super class of both and implements List<String>). The latter being the most specific type that Mocha can infer for y after the conditional. In languages like Scala, C#3.0 and OCaml, such code cannot be written since variables must have a single fixed type for the life of the method.
Allowing variables to have different types at different program points also means they can be retyped as a result of instanceof expressions. For example:
void f(Number x) {
if(x instanceof Integer) {
...
}
}
Here, Mocha automatically retypes variable x to Integer inside the true-branch of the conditional. Again, languages like Scala, C#3.0 and OCaml cannot support this.
Download
| Release | Date | Arch | Files | Notes |
| 0.1 | Aug 2008 | UNIX (inc. Linux) | mocha.tgz | ![]() |
| © David J. Pearce, 2008 | [an error occurred while processing this directive] |
