Totality at switch statements
Hunor Szegi
hunor.szegi at gmail.com
Tue Jun 21 09:44:10 UTC 2022
Thank you. Yes, that is the best we can do if we want to know about the
changes, listing the cases we are aware of, using a concise syntax. With
leftovers it would be possible listing multiple type patterns under a
single label. Currently it is possible only using multiple case entries. I
could imagine a syntax like this: case (BadCase, ReallyBadCase, AwfulCase)
i -> .... but here the i should be an Object type - or the lowest common
type. (In spite of that it isn't the same as "case Object i ->")
BTW, playing with the syntax I realised Java 18 accepts both the "default"
and "case default" labels (using legacy and arrow syntax as well). Java 8
accepts only "default". (In the specs I found only this format.)
On Mon, 20 Jun 2022 at 15:45, Brian Goetz <brian.goetz at oracle.com> wrote:
>
>
> 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/20220621/21874832/attachment.htm>
More information about the amber-dev
mailing list