I think switch should be optionally null-friendly, and the path you’ve sketched is a very simple way to get that outcome.
On Jan 8, 2020, at 12:55 PM, Brian Goetz <[email protected]> wrote: > > The main costs are two: > - a `default` is not the same as `case _` or `case var x` or `case Object x`; It would be nice to say “default is sugar for case any” but it’s just “nice”, not essential to the story of switch. As a legacy construct “default” is always going to be an outlier. For example, it can be reordered with respect to other cases in legacy switches at least. I think it is a legitimate move to “blame default” for null hostility, as part of the legacy quirks. I *don’t* think this is in any way harder to learn or use than the alternatives. > - the mental model that switches are null-hostile needs to be shifted to > "switch defaults are null-hostile.” Among the various mental model shifts for switch this is trivial. Let’s not obsess on it. The “switch doesn’t handle null” meme is no more sacred than “switch only applies to certain types” or “switch only applies to constant expressions”. All such memes can be readily discarded under the rubric of “Java is now removing previous limitations on existing constructs.” Anybody who welcomes this extension to Java should welcome null handling along with all the other extensions. Yes, null is a singular value, but it is not always an inappropriate one. And a general-purpose construct (like switch or instanceof) should not make policy decisions like “we don’t serve nulls here”. (Throwing NPE on an actual method or field access is deeper than mere policy: In that case there’s really no method or field to observe through the null. Throwing NPE on the mere examination of a null, a la Objects.requireNonNull, is the enforcement of a non-essential policy. That’s not a good job for Java syntax.) The benefit of moving the null-hostility from “switch” down to “default” (“blame it on default”) is that switch becomes competent to deal, uniformly, with all values expressible in Java. Instead of all values expressible in Java except null. — John
