[pattern-switch] Opting into totality

Dan Smith daniel.smith at oracle.com
Tue Sep 1 01:56:21 UTC 2020

> On Aug 31, 2020, at 5:04 PM, Remi Forax <forax at univ-mlv.fr> wrote:
> Given that if there is a default it's already a sealed switch and that i can add a default to make it a sealed switch,
> i struggle to see where to use a classical statement switch and where to use a sealed switch ?

A competent programmer will definitely need to be able to answer the question "should I add 'sealed' to this switch?" I'll take a stab at enumerating all the cases:

- A switch statement with a 'default' case: doesn't matter. The language already supports 'default' in both forms (existing switch statements are non-sealed, existing switch expressions are sealed). Pick a favorite style. (Alternatively: a switch statement with a 'default' clause is implicitly sealed. Then it's a style question of whether or not to be explicit about it.)

- A switch statement that initializes a local variable or returns at the end of a method: doesn't matter. If you don't say 'sealed', flow analysis will catch any mistakes. (But there are some gotchas, so maybe 'sealed' (or switch expression) is the way to go if you don't want to think about it.)

- A switch statement that side-effects on just a few of the possible inputs ("possible" per static types): must use a non-sealed switch.

- A switch statement that is optimistically total over an enum/sealed class: use a sealed switch to ensure totality checking in the future. Or, if the totality is accidental (I cover the cases right now, but don't expect to in the future), use a non-sealed switch.

- A switch statement with a last 'case' intended to be total: use a sealed switch to avoid mistakes and (if it's a risk) defend against input type changes

I think that covers it? There will be some coding style preferences to work out, but I think this story will be intuitive to most programmers.

More information about the amber-spec-experts mailing list