LoginSignup
0
0

Dart3.0 switch case pattern matching

Posted at

switch case

switch文でビジネスロジックを解く問題をやっていたときに、ふと気づいたことがありました。昔からあるcase文で書くとコードの記述量が長かったことに!

問題はこれ!

ある一つの引数をつる関数を作る。条件によって値を出力する。季節の値を返してもらう。

[Dart3.0以前の書き方]
case文を複数書く。なんだ冗長ですね。いや普通なのか?

String showSeason(int month) {
  switch(month) {
    case 3:
    case 4:
    case 5:
      return '春';
    case 6:
    case 7:
    case 8:
      return '夏';
    case 9:
    case 10:
    case 11:
      return '秋';
    case 12:
    case 1:
    case 2:
      return '冬';
    default:
      return '季節不明';
  }
}

void main() {
  print(showSeason(3));  // 春
  print(showSeason(6));  // 夏
  print(showSeason(9));  // 秋
  print(showSeason(12)); // 冬
  print(showSeason(13)); // 季節不明
}

Dart3.0 からはパターンマッチング使用できる。
https://dart.dev/language/patterns

[使用例]

switch (obj) {
  // Matches if 1 == obj.
  case 1:
    print('one');

  // Matches if the value of obj is between the
  // constant values of 'first' and 'last'.
  case >= first && <= last:
    print('in range');

  // Matches if obj is a record with two fields,
  // then assigns the fields to 'a' and 'b'.
  case (var a, var b):
    print('a = $a, b = $b');

  default:
}

[pattern matching]
論理演算を使うことでコードの量を22行から14行に削減できた!

String showSeason(int month) {
  switch(month) {
    case 3 || 4 || 5:
      return '春';
    case 6 || 7 || 8:
      return '夏';
    case 9 || 10 || 11:
      return '秋';
    case 12 || 1 || 2:
      return '冬';
    default:
      return '季節不明';
  }
}

void main() {
  print(showSeason(3));
  print(showSeason(6));
  print(showSeason(9));
  print(showSeason(12));
  print(showSeason(13));
}

コードの記述量の削減をDart3.0から追加されたパターンマッチングで削減してみました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0