Skip to content

Instantly share code, notes, and snippets.

@drager
Last active July 13, 2017 22:58
Show Gist options
  • Save drager/041420ef3e73c84a320d to your computer and use it in GitHub Desktop.
Save drager/041420ef3e73c84a320d to your computer and use it in GitHub Desktop.

Case 1

match(10) {
  w < 10 => print('x is less than 10');
  x > 10 => print('x is greater than 10');
  10 => print('x is equal to 10');
}

Case 2

match(90) {
  m is int => print('x is an integer');
  x is num => print('x is another type of number');
  90 => print('x is equal to 90');
}

Case 4

match(new Point(2, 5)) {
  Point {x: 2, y} => print('x is 2, y is $y');
  Point {x, y: 5} => print('x is $x, y is 5');
  Point {x, y} => print('x is $x, y is $y);
}

Case 5

match([2, 5]) {
  [2, b] => print('x is 2, b is $b');
  [a, 5] => print('x is $a, b is 5');
  [a, a] => print('the zero and first indices are $a');
  [a, b] => print('a is $a, b is $b');
  _ => print('list has a different size than 2');
}

Case 6

match(10) {
  x % 2 == 0 => print('x is even');
  x % 2 == 1 => print('x is odd');
}

Case 7

match(10) {
  x >= 10 && x <= 11 => print('x is 10 or 11');
  x < 10 || x > 11 => print('x is something else');
}

Case 8

Error:

dynamic a = 10
match(a) {
  0 => print('x is 10 or 11');
  1 => print('x is something else');
  num => print('x is a num');
}

Use case

fib(int n) => match(n) {
  0 => 0;
  1 => 1;
  n => fib(n-1) + fib(n-2);
}

Valid operators in a match expression is:

  • <
  • <=
  • =

  • ==
  • is

If there's only one object the == operator is used for comparison with the match object.

if (x is Point && x.x == 2 && x.y == x.y) {
  var x = x.x;
  var y = x.y;
  print('x is 2, y is $y');
} else if (x is Point && x.x == x.x && x.y == 5) {
  var _ = x;
  var x = _.x;
  print('x is $x, y is 5');
} else if (x is Point && x.x == x.x && x.y == x.y) {
  var _ = x;
  var x = _.x;
  var y = _.y;
  print('x is $x, y is $y);
}

Additional possibilties

match(9) {
  x is int && 1...10 => print('x is in range 1 to 10');
  _ => print('x is not in range 1 to 10');
}
if (x >= 1 && x <= 10) {
  print('x is in range 1 to 10');
} else {
  print('x is not in range 1 to 10');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment