Skip to main content

Function that does not return normally II (the return)

Posted by forax on September 8, 2006 at 6:08 AM PDT

In a previous entry, i've written about declaring a method
that doesn't return normally using null,
the type of null, as return type.
A comment from Neal Gafter make me realize that i was wrong
but i now think the closure spec is wrong too.

What the closure proposal says is that a function that doesn't
return normally should use null.
Not the converse, so i agree with neal that a method that use
null as return type doesn't allow the compiler to
flag the method as "never returned", perhaps the method
always returns null.

But the closure proposal is wrong too,
if a function that never returns is typed null
its function type can't be a subtype of
the type of a function that returns a primitive type.

So the example below will not compile :

 null(void) f={
   throw RuntimeException();
int(void) g=f;

The assumption of the closure proposal is that a function that
never return has a return type that is a subtype of null.
This is clearly wrong with the current Java type system
because boxing relations are not subtyping relations.

I propose to introduce throws as
the return type of a method that never returns,
with the following subtyping rules :

 Object < Integer < null < throws
int < throws

Using throws as several avantages upon null for method that doesn't return normally because :

  1. a function that returns throws is a subtype of
    a function that returns a primitive type.

  2. users can declare methods that doesn't return normally
    and the compiler can understand that.

I wait your comments.

Related Topics >>