java.lang.Unreachable as type argument
The closure proposal specifies a new type java.lang.Undeclarable that can be used as a return type of a method to indicates that this method never returns. All instructions after a call to a method that returns Undeclarable is unreachable, by example :
Undeclarable throwAnIOException(String message) throws Exception {
throw new IOException(message);
}
...
void foo() {
...
throwAnIOException("oups");
return; // this code is unreachable
}
This type is needed because in the closure proposal, the closure (return) type is infered from the type its last expression. So if the last expression is a throw, the compiler will infer java.lang.Undeclarable.
Now, the proposal also provides an example of code in which Unreachable is used as argument of a type variable.
interface NullaryFunction<T, throws E> {
T invoke() throws E;
}
NullaryFunction<Unreachable,null> thrower = {=> throw new AssertionError(); };
'Return' type variable
But Undeclarable can only be used as a return type
and the compiler will not enforce that.
I propose to tag the type variable with the keyword return
to say that type variable can only be used as return type,
with the following rules
- Its a compile error to use Undeclarable as a type variable not tagged by return.
- Its a compile time error to use a type variable tagged by return in any other places that as return type
With these rules, the previous example will be:
interface NullaryFunction<return T, throws E> {
T invoke() throws E;
}
NullaryFunction<Unreachable,null> thrower = {=> throw new AssertionError(); };
The closure proposal already describes a resticted type variable: the throws type variable. A type variable tagged by throws that can be only used in throws clause and used a special inference mecanism. So adding a return type variable is just another way to restrict a type variable.
Self typesIn a recent blog entry, Peter ahé's describes Self types, he write in an answer to one of my comment, "The this type variable is only type-safe in covariant places". So like Undeclarable, if we want to use this as a type argument, the corresponding type variable should be tagged by return.
I wait you comments.
Rémi
- Login or register to post comments
- Printer-friendly version
- forax's blog
- 761 reads





