Totality at switch statements

Brian Goetz brian.goetz at oracle.com
Mon Jun 20 14:45:19 UTC 2022



> Looking at your example, when an additional sealed subclass will be 
> added. Yes, it would be very useful to warn the programmers. But 
> imagine a situation when the totality isn't intended, so the 
> programmer wants a side effect only in a few cases. She will be forced 
> to add an empty default clause. And later, when a new sealed subclass 
> will be added, there won't be any alert, as the switch is already 
> total, forever. Surely, it helped a little bit to increase the safety 
> initially (the programmer was forced to think about the missing 
> cases), but with a lot of empty default clauses this safety will be 
> partial.

Well, it depends how many cases your sealed type has.  If it has few, 
then you can totalize by naming all the cases.  Now, right now that is a 
little cumbersome, but in the future you will probably be able to do:

     switch (x) {
         case GoodCase g: ...
         case AlsoGoodCase g: ...
         case BadCase _, ReallyBadCase _, AwfulCase _: throw ...
     }

which, depending on how many permitted types there are, still preserves 
the "tell me when something changes" behavior.  (You can't do this now 
because you can't merge patterns with bindings, and you can't yet 
suppress a binding.  All in due time.)

> BTW, Scala allows switch expressions without totality, only a warning 
> is raised. This seems a safety risk to me, no idea why it was 
> implemented this way.

FWIW, Haskell also allows functions defined by case to be partial too.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220620/1c79b47c/attachment.htm>


More information about the amber-dev mailing list