> On Jan 10, 2020, at 11:03 AM, Brian Goetz <brian.go...@oracle.com> wrote: > > I don't want to dive into a design discussion on declared patterns, but I > think we can resolve most of the nullability issues without doing so. > > Like methods, declared patterns are members. Like methods, they can be > static or instance. > > If they are instance, the target is the receiver, and that surely won't work > if the receiver is null. So by definition, instance patterns cannot match > null. Let's set that aside. > > (Example: an instance pattern is a pattern on a class, like: > > switch (aString) { > case palindrome(var firstHalf, boolean isOdd): ... > } > > where palindrome is an instance pattern on String.) > > Declared patterns have a target type (may want a better name), which for an > instance pattern is the receiver type, and for a static pattern is part of > the declaration. (For example, `Optional.of(var x)` has a target type of > `<T> Optional<T>`.) > > We won't even try to match the pattern unless the match target is of the > target type for the pattern (it's not an Optional.of(anything) if its not an > Optional to begin with.) So we have to do some sort of test first -- either > instanceof (in which case static pattern will never match null, period), or a > type pattern match (which would be the more principled choice, and would only > admit a null through to the user-written code if the target type of the > static pattern were total on the operand of the switch/instanceof.) > > So it's already a pretty narrow case where a null would be admitted into the > user code at all. Now, the finishing blow: do we really want to ask the > authors of the `Optional.of(var x)` and `Optional.empty()` patterns to have > to check their target for null? That would be creating a million new bugs to > accommodate a handful of corner cases. > > Which brings us back to ... > > Only the top (total) and bottom (null constant) patterns match null. Guy is > happy again. (And the crowd goes wild.)
Nice bit of reasoning, and I am indeed happy again. (I was hoping I would have to write “switch?” exactly once in my life. Well, this makes twice. But this isa much better solution.) —Guy