Here is a simple dart program with a switch statement.
void main() {
var list = [1, 2];
var set = <int>{1, 2};
var map = <int, int> {1: 2, 3: 4};
switch (list) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int> {1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
As I understand in the dart lang, the switch statement does not check == for every case, but rather it does pattern matching.
In the above code, when the expression is switch(list), the console prints 2. When it is switch(set), the console does not print anything, and for switch(map), the console prints 4.
Questions:
switch(set), the switch does not print 3?const is required for Set, and not for List and Map?
If I remove const in the set case, I get an error message :The expression of a constant pattern must be a valid constant.
Dart supports the following types of patterns:
Notice that both List and Map have built-in pattern types, while Set does not.
There is however a constant pattern, which allows for case const <int> {1, 2}:.
Also consider this:
void main() {
print(const <int> {1, 2} == <int> {1, 2}); // false
print(const <int> {1, 2} == const <int> {1, 2}); // true
}
So with that in mind, the following:
void main() {
var list = [1, 2];
var set = const <int>{1, 2}; // add const
var map = <int, int> {1: 2, 3: 4};
switch (set) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int> {1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
prints 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With