Disallowing break label (and continue label) inside an expression switch
    Guy Steele 
    guy.steele at oracle.com
       
    Fri Mar 23 20:51:22 UTC 2018
    
    
  
  String s = switch (e) {
	case 0 -> break “foofoo”;
	case 1:
		if (p == 0) break x;
		else { String z = hairy(x); break z+z; }
	case 2 -> “barbar”;
  };
Now I decide that case 1 has three subcases.  So I change the `if` to a statement `switch`.
  String s = switch (e) {
	case 0 -> break “foofoo”;
	case 1:
		switch (p) {
			case 0: break x;
			case 1: break x+x;
			default: String z = hairy(x); break z+z;
		}
	case 2 -> “barbar”;
  };
FAIL.
One can argue that I should have done something else, such as use a three-way if-then-else:
  String s = switch (e) {
	case 0 -> break “foofoo”;
	case 1:
		if (p == 0) break x;
		else if (p == 1) break x+x;
		else { String z = hairy(x); break z+z; }
	case 2 -> “barbar”;
  };
or use a switch expression rather than a statement switch:
  String s = switch (e) {
	case 0 -> break “foofoo”;
	case 1 ->
		switch (p) {
			case 0 -> x;
			case 1 -> x+x;
			default: String z = hairy(x); break z+z;
		}
	case 2 -> “barbar”;
  };
All I’m doing is demonstrating that a common refactoring pattern “turn the `if` statement into a `switch` statement” has more pitfalls than it used to once we introduce `switch` expressions.
—Guy
    
    
More information about the amber-spec-experts
mailing list