ceylon/ceylon-spec — Issue #74: narrow type in else block of if (is...)
Author: gavinking
Created: 2011-11-26 17:35:56+00:00
State: open

Tako gives this example:

shared Natural q(Natural? x) {
if (is Nothing x) {
return 0;
}
else {
return x; //compile error
}
}

He argues, rather reasonably, that the compiler should be able to reason that `x` has type `Natural` where the error occurs.

I agree that it would be possible. This would not amount to supporting types like `X~Y`, which Ross says results in undecidability, if I recall correctly. It just means being able to utilize the identity `X|Y~Y == X`, which we already do utilize in certain places.

On the other hand:

1. This example is a bit contrived. It would be *much* more usual to reverse the condition to do `if (is Natural x)` or `if (exists x)`.
2. For more complex cases, this is stepping on the turf of the `switch` statement.

So I'm not sure that this feature would really be especially practically useful. OTOH, it's easily doable.