Feedback on nulls in switch

Stephen Colebourne scolebourne at joda.org
Tue Aug 11 06:35:47 UTC 2020


On Tue, 11 Aug 2020 at 01:43, John Rose <john.r.rose at oracle.com> wrote:
> On Aug 10, 2020, at 4:03 PM, Stephen Colebourne <scolebourne at joda.org> wrote:
> >
> > Given:
> >  box instanceof Object o
> > o is non-null. And given:
> >  switch (box) {
> >     case Box b:
> >  }
> > b is non-null.
>
> That latter is not necessarily true and I think you need a better example.
> The b can be null because the case is the last case and therefore (not otherwise) may be total.

Yuck.. Yucky yuck.

> When I see the last case in a switch I expect it to be a catch-all, don’t you?

No. I expect it to go through the switch statement without matching
anything. Only a default clause is a catch all.
(As a reminder, most devs haven't used a switch expression yet, and
those expressions still need a default clause unless they are an enum)

> I think we all are going to have to learn to read the bottom of a switch as a probable catch-all.
> Maybe we want to add a modifier to enforce the assumption, and exclude the implicit default; I’ve suggested ‘final case’ as a cite bikeshed color.

:-) I woke up this morning and had almost exactly this thought. I
think all my concerns go away with this syntax/semantic:

  switch (box) {
     case Box(Chocolate c):
     case Box(Frog f):
     default Box(Object o):  // matches null
  }

  switch (box) {
     case Box b:  // does not match null
     default Box n:  // matches null (only null in this example)
 }

If you use a switch statement and use `case Box(Object o)` last it
only matches non-null just like it should and the statement is not
total.
If you use a switch expression and use `case Box(Object o)` last it
doesn't compile as the last case is not total.
If you use a switch expression you need either a simple `default:` or
a matching default `default Box(Object o)` last to make it total.
var is just simple type inference.
I think this means a switch could have multiple defaults when there
are subtypes, but that seems OK.

Stephen


More information about the amber-dev mailing list