Description
I'm not sure if this is a bug but when I switch over a double and exhaustively match all possible values (I think), Dart still forces me to add an additional case.
final steering = switch (bearingDifference) {
< 0 => SteeringInstruction.right,
> 0 => SteeringInstruction.left,
== 0 => SteeringInstruction.straight,
};
The code above gives this compile time error:
Error: The type 'double' is not exhaustively matched by the switch cases since it doesn't match 'double()'.
Try adding a wildcard pattern or cases that match 'double()'.
Now it might be that I'm really missing a case but the error isn't very helpful here. Am I missing double.nan
? (No, because "A double can't equal 'double.nan', so the condition is always 'false'.") Is it double.infinity
and double.negativeInfinity
? (No, those values are already covered, and adding them doesn't make a difference.) Is it -0
? (No. Adding -0
doesn't make a difference.) Is it null? (No, the number is non-nullable.) A specific suggestion would be much more helpful.
Or maybe it's that Dart doesn't know (can't prove) what's missing for continuous values such as double
. If that's the case, the error should note that. Something like "Switching over real numbers is not supported. You have to include a default
case, even if you know it will never be matched."
Thankfully, the workaround is easy:
final steering = switch (bearingDifference) {
< 0 => SteeringInstruction.right,
> 0 => SteeringInstruction.left,
== 0 => SteeringInstruction.straight,
_ => throw StateError(
'Double $bearingDifference somehow '
"doesn't belong on the number line and Dart won't tell us why. ¯\_(ツ)_/¯"),
};
;)
Dart info
- Dart 3.5.4 (stable) (Wed Oct 16 16:18:51 2024 +0000) on "macos_arm64"
- on macos / Version 14.7 (Build 23H124)
- locale is en-US