Home > Software engineering >  Additional constant value in enum prevents exhausting switch statements
Additional constant value in enum prevents exhausting switch statements

Time:11-03

I have following enum:

enum PlayButtonState {
  loading,
  paused,
  playing;

  static const defaultValue = PlayButtonState.paused;
}

Here's a function to retrieve display-string for PlayButtonState:

String _getPlayButtonStateStr(PlayButtonState state) {
  switch (state) {
    case PlayButtonState.loading:
      return "loading";
    case PlayButtonState.paused:
      return "paused";
    case PlayButtonState.playing:
      return "playing";
  }
}

Here's a program to run it:

main() {
  final currentState = PlayButtonState.values[1];
  final currentStateText = _getPlayButtonStateStr(currentState);
  print("current-state: $currentStateText");
}

If you run the program, it fails with following exception:

Error: A non-null value must be returned since the return type 'String' doesn't allow null. String _getPlayButtonStateStr(PlayButtonState state) {...}

If I add an additional case PlayButtonState.defaultValue to switch-statement, program runs without error. But, this gives me following warning:

Do not use more than one case with same value (PlayButtonState.defaultValue and PlayButtonState.paused) (Documentation)

My question is Why? Is it wrong to define a const variable in enum like this? Android Studio doesn't show any error or lint to point this out.

If this is expected and documented, please either give me a link or explaing how it works.

CodePudding user response:

This is a bug, cf. https://github.com/dart-lang/sdk/issues/50354.

(here's a bunch of extra characters, such that SO is happy)

  • Related