Using constant patterns with type literals is most likely a mistake.
For example, the following code
bool isANumber(Object? o) {
if (o case num) { // Checks if `o` is `num`, not if it is a `num`
return true;
}
return false;
}
will always return false
for any input value of type num
(as in isANumber(42)
), and will
returns true
only when the input is the type num
(as in isANumber(int)
).
This is because a constant pattern compares the value of the provided constant against the value being matched, and not against its type.
The original intent of checking whether an Object? o
is a num
or not, should be expressed via a typed variable pattern:
bool isANumber(Object? o) {
if (o case num n) { // Checks if `o` is a `num` and assigns the cast value to n
return true;
}
return false;
}
If the intent of the code is to only check whether the input is a num
or not, then the n
variable is not necessary, and a
value discard can be used:
bool isANumber(Object? o) {
if (o case num _) { // Checks if `o` is a `num`, and discards the cast value
return true;
}
return false;
}