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

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

On Jan 8, 2020, at 11:52 PM, Peter Levart <peter.levart at gmail.com> wrote:
> I'm just thinking if such arrangement allows expressing all possible situations that may arise in a switch.
> Imagine one wants to switch on (Object o) and have the following cases:
> - String: case 1
> - CharSequence or null: case 2
> - any other: case 3
> How would one structure such switch? Would case 2 have to be split before and after case 1?

Either, I think.  Coder’s choice, based on taste, coding style
norms, and the shape of the problem.  Note that if “case null”
comes first, it’s really easy to tell that the switch accepts null,
and that’s probably the right answer most of the time.  But if
“case null” follows “case String”, we still get the same decision
tree (in a different lexical form), because “case String”, being
non-total (the switch is on “Object o”), excludes null.  For the
same reason, “case null” could also go *after* “case CharSequence”.

switch ((Object)o) {
//OK placement// case null: return 2;
case String: return 1;
//OK placement// case null: return 2;
case CharSequence: return 2;
//OK placement// case null: return 2;
case Object:
   //OK workaround// if (o == null)  return 2;
   return 3;

Any of the individual “//OK*//” lines could be uncommented
to get the same decisions.

As Brian said, since we don’t have plans to do T? patterns
or binding merging, that’s as good as it gets.  We want to
avoid adding more machinery just to favor these use cases.
IMO *simple* support for nulls is a glass 99% full, but clearly
there’s a 1% effect from use case like these.  Java is full of
such 99% full features.

We haven’t yet moved on to library-defined patterns (“static
patterns”).  To gaze a bit into the crystal ball:  I think it’s
likely that those will provide a way to express T? using
a library API instead of a language primitive.  We should
defer building out that last 1% of null support either
indefinitely, or until there is a way for libraries to define
their own kinds of patterns.  In the latter case the cost
of adding a nullable pattern is likely to be lower than
the alternatives on the table, since library changes are
always cheaper than language changes.

— John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20200109/ec41faee/attachment.htm>

More information about the amber-spec-experts mailing list