Exhaustive enum switch results in “missing end return” diagnostic

enum X {
  A,
  B,
  C
}

String getStringFromX(X x) {
  switch (x) {
    case X.A: return "A";
    case X.B: return "B";
    case X.C: return "C";
  }
}

[dart] This function declares a return type of ‘String’, but doesn’t end with a return statement.

If you add a default case to that switch the diagnostic goes away.

Author: Fantashit

4 thoughts on “Exhaustive enum switch results in “missing end return” diagnostic

  1. This is working as intended.

    In Dart, enums are objects, like everything else, so there’s another valid value for x: null. If null is passed as an argument to this method, then none of the cases will be selected and the switch statement will fall through. By default it will return null, but that’s rarely what’s intended, so we warn you.

    If that is what you intend, then you can work around this by adding an explicit return null; at the end of the method, or add an ignore comment to disable the warning.

  2. This is totall bullshit if you ask me, and for a modern language, this is utter nonsense. Just take a look at how it should be done, e.g. in Kotlin

  3. String getStringFromX(X x) {
      if (x == null) return "";
      switch (x) {
        case X.A: return "A";
        case X.B: return "B";
        case X.C: return "C";
      }
    }
    

    This is absolutely safe, but still the warning is present.
    Adding default to the switch or return to the end of the method ISN’T safe. If I add a new value to the enum I’ll get no warnings.

  4. Note that when the upcoming null-safety support arrives, the enum type X will be a non-nullable type, and the need to check for null will disappear.

Comments are closed.