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.
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.
I see. Thank you @bwilkerson.
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
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.
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.
Most helpful comment
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