Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement in dart with set expression

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:

  1. Why when the expression is switch(set), the switch does not print 3?
  2. Why 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.

like image 548
Anonymous Avatar asked Dec 05 '25 23:12

Anonymous


1 Answers

Dart supports the following types of patterns:

  • Logical-or
  • Logical-and
  • Relational
  • Cast
  • Null-check
  • Null-assert
  • Constant
  • Variable
  • Identifier
  • Parenthesized
  • List
  • Map
  • Record
  • Object
  • Wildcard

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.

like image 88
mmcdon20 Avatar answered Dec 08 '25 01:12

mmcdon20