Thanks for bringing this up.  I remember it being discussed once before, but I don't think we acted on it.

I agree that expression switch is an expression, and it should either yield a value or throw something; breaking out of the middle of an expression is not something we have, nor does it seem necessary. (Though I'm sure clever folks could come up with a good example where it would be convenient.)

A sensible extension of this is no "return" from a switch expression either:

    int foo(int x) {
        return switch (x) {
            case 1 -> 2;
            case 2 -> 4;
            case 3 -> 8;
            default: return Integer.MAX_VALUE;
        }
    }

Like conditionals, then, switch expressions would either yield a value (through breaking) or throw.  This seems consistent, but...what happens when we nest a statement in a switch expression?

    void foo(int x, int y, int z) {
        TOP:
        switch (z) {
            case 1:
                int i = switch (x) {
                    case 1 -> 2;
                    case 2:
                        switch (y) {
                            case 1: return;
                            default: break TOP;
                        }
                }
        }
    }

Do we disallow the "break TOP" and return in the inner switch? IOW, does the expression form a barrier through which control can only pass via break or exceptions?





On 3/2/2018 9:30 AM, Remi Forax wrote:
Hi all,
as far as i remember, the current idea to differentiate between a break label 
and a break value is to let the compiler figure this out,
i wonder if it's not simpler to disallow break label (and continue label) 
inside an expression switch.

After all, an expression switch do not exist yet, so no backward compatibility 
issue, it may make some refactoring impossible but had the great advantage to 
do not allow a lot of puzzler codes like the one below.

enum Result {
   ONE, MANY
}

Result result(String[] args) {
   ONE: for(String s: args) {
      return switch(s) {
        case "several":
        case "many":
          break MANY;
        case "one":
          break ONE;
        default:
          continue;
      };
   }
   throw ...;
}

Rémi

Reply via email to