相关文章推荐

Using => in switch statements is confusing #2126

@Hixie

Description

https://github.com/dart-lang/language/blob/master/working/0546-patterns/patterns-feature-specification.md proposes this syntax:

Color shiftHue(Color color) {
  return switch (color) {
    case Color.red => Color.orange;
    case Color.orange => Color.yellow;
    case Color.yellow => Color.green;
    case Color.green => Color.blue;
    case Color.blue => Color.purple;
    case Color.purple => Color.red;
bool xor(bool a, bool b) =>
    switch ((a, b)) {
      case (true, true) => false;
      case (true, false) => true;
      case (false, true) => true;
      case (false, false) => false;

I've been trying to come to terms with this re-use of => for a few days now and I am still finding it very confusing. I understand the logic path that leads to this design (=> is sort of "define the thing on the left as returning the expression on the right") but I can't help but read it as "define a function with the arguments on the left and the return value on the right". Seeing (true, true) => false not be a lambda is quite disorienting IMHO.

It seems to be to be somewhat unnecessary, too. switch could be defined as it is now, modulo removing the requirements for break, and allowed anywhere an expression is allowed, with the exception that if any of the cases have more than one statement, or if any of the cases evaluate to a value that isn't compatible in the expression where the switch is used, then the switch is invalid. (The error messages can be carefully designed to make this intuitive, IMHO.)

Color shiftHue(Color color) {
  return switch (color) {
    case Color.red: Color.orange;
    case Color.orange: Color.yellow;
    case Color.yellow: Color.green;
    case Color.green: Color.blue;
    case Color.blue: Color.purple;
    case Color.purple: Color.red;
bool xor(bool a, bool b) =>
    switch ((a, b)) {
      case (true, true): false;
      case (true, false): true;
      case (false, true): true;
      case (false, false): false;
    };
 
推荐文章