[patterns] Nullability in patterns, and pattern-aware constructs (again)

John Rose john.r.rose at oracle.com
Fri Jan 10 21:00:15 UTC 2020


On Jan 10, 2020, at 12:00 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> 
> SO, proposed: disallow "any" patterns (_, var x, or total T x) in instanceof.  Instanceof is for partial patterns.

+1.  Total patterns belong at the bottom of a decision tree, not in an instanceof.

Hmm.  This affects desugaring of switch.  Maybe the final, total case of a switch
is desugared by a let instead of an if/instanceof.  It makes the desugaring depend
on whether the final case is total or not, which depends on types.  I think that’s
an OK thing to do; it makes clear how totality affects translation.

> Note that 
> 
>     Point p;
>     if (p instanceof Point(var x, var y)) { }
> 
> is total, but we would't want to disallow it, as this pattern could still fail if p == null.  

Ooh, that’s a tricky corner case.  There’s an argument for saying
“that’s total *and* null-hostile”, by analogy with “if (anInteger == 0)”.

But I suppose instanceof should never throw, so returning false for null
there is OK.

> We might want to go a little further, and ban constant patterns in instanceof too, since all of the following have simpler forms:
> 
>     if (x instanceof null) { ... }
>     if (x instanceof "") { ... }
>     if (i instanceof 3) { ... }
> 
> Or not -- I suspect not.

One reason to keep it is floats:

  if (x instanceof Float.NaN) { … }

This seems to be a fine thing for an IDE to warn about, and not
so fine for a language to legislate.

— John



More information about the amber-spec-experts mailing list