Switch labels (null again), some tweaking
Brian Goetz
brian.goetz at oracle.com
Wed Apr 28 23:01:56 UTC 2021
On 4/28/2021 5:34 PM, Maurizio Cimadamore wrote:
>
> Thanks for this.
>
> It is especially helpful to see all the rules in a single place.
>
> So, armed with these rules - back to the first example I brought up:
>
> switch (lunch) {
> case Box(Soup s) {
> if (s == null) {
> System.err.println("Box of null");
> } else {
> System.err.println("Box of soup");
> }
> }
>
> case Bag(Soup s): {
> if (s == null) {
> System.err.println("Bag of null");
> } else {
> System.err.println("Bag of soup");
> }
>
> }
> }
>
> If I read the rules correctly, Box(Soup) + Bag(Soup) "cover"
> Container<Lunch>, with the exception of the { null, Box(null),
> Bag(null) }. So the above will throw when `lunch` is null, and will
> also throw with Box(null) or Bag(null). Correct?
>
Correct (under the "we make switches total" plan.)
> So the right way to write that would be to add a couple of { case
> Box(null), case Bag(null) } - these will reduce the remainder of the
> switch blanket to just { null } - which means the switch will just
> throw on a null input value, as usual.
>
Correct. Any of the following would work to capture the remainder
explicitly (not all of these are valid syntax, though):
case null, Box(null), Bag(null): // explicit remainder
case null, Box, Bag: // basically the same
case null, default: // default misses null, so we add it in
case null, Container(null): // another way to say the same thing
case Container c: // total pattern, catches everything
More information about the amber-spec-experts
mailing list