Sdk: Exhaustive switch case statements consisting of return statements do not satisfy function return requirements

Created on 17 May 2018  Â·  7Comments  Â·  Source: dart-lang/sdk

Seeing this using dartpad: https://dartpad.dartlang.org/ (Based on Dart SDK 1.25.0.)
Also seeing in Flutter:

Flutter 0.3.1 • channel beta • https://github.com/flutter/flutter.git
Framework • revision 12bbaba9ae (4 weeks ago) • 2018-04-19 23:36:15 -0700
Engine • revision 09d05a3891
Tools • Dart 2.0.0-dev.48.0.flutter-fe606f890b

I am developing on a Mac.


When I have a switch statement over an Enum, that is exhaustive, if each branch of the switch case has a return statement, I still get an info in the compiler indicating the function does not end with a return statement. Inserting a return statement at the end of the function removes this error, despite the fact that I believe this statement cannot execute under any circumstances.

This is demonstrated in this 5 line dartpad.

enum Foo {A, B}

String myFunc(Foo f) {
  switch(f) {
    case Foo.A: return "A";
    case Foo.B: return "B";
  }
}
area-analyzer closed-as-intended

Most helpful comment

Agreed. You could always use default:

All 7 comments

@danbrotherston Unfortunately f can also be null:

myFunc(null);

Gross.

Thanks for clarifying.

I do find it strange that I don't get a "non-exhaustive" error in that case, and worse, I cannot even make a case statement for null.

This could lead me to write buggy code. I don't normally think of Enums as the type of things that can be null.

Agreed. You could always use default:

I don't normally think of Enums as the type of things that can be null.

Similar with bool variables.
Hopefully we will get #22 (see also #27231) eventually

FWIW I am getting the same warning if in this case:

enum Foo {A, B}

extension Bar on Foo {
  String get value {
    switch (this) {
      case Foo.A: return "A";
      case Foo.B: return "B";
    }
  }
}

In this example I don't think this being null is the cause of the warning. Can anyone shed some light as to what's going on here?

Demonstrated here: https://dartpad.dartlang.org/cf1bf7267acffb795ddbf75fc3b71cbe

@vrutberg static extension methods are just another syntax for static calls, which means that this in an extension method can actually be null. Try something like this:

enum Foo {A, B}

extension Bar on Foo {
  String get value {
    switch (this) {
      case Foo.A: return "A";
      case Foo.B: return "B";
      default:
        print('this=${this}');
    }
  }
}

void main() {
  Foo x = null;
  print(x.value);
}

@mraleph Oh, alright. Thanks for shedding some light on that, that does explain the warning.

Was this page helpful?
0 / 5 - 0 ratings