0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dartの言語仕様 制御構文

Posted at

制御構文

一般的なプログラミング言語と同様に、下記のような制御構文を利用可能

  • if
  • for
  • for-in
  • forEach
  • while
  • do-while
  • switch

whenキーワード

if や switch 制御構文では、case キーワードと when キーワードを利用して条件を追加することが可能

final (String?, int?) response = ('OK', 200);
if(response case (String message, int statusCode) when statusCode==200){
    print('Response: message:$message, statusCode:$sutatusCode');
} else {
    print('No Response received.');
}

case キーワード部分ではパターンマッチングが働いている
when キーワード部分では case によって分解された変数に対しての条件を追加している
通常のif文でも代用は出来そうだが、caseは基本的には型判別に用いるということなのだろう。

switchに対してのcaseは、私の中でイメージとして”条件”だったが、言われてみるとパターンマッチングなのか。。うーん。

ちなみに、先の例でいうならば変数responseが型としてマッチングした際に処理を走らせるというのであれば、”特定のフィールドや関数を持つ”というような部分的なマッチングが出来ないかと思ったが、どうやらあくまで型判別であるようで出来なかった。

sealed class Shape {}
class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}
class Rectangle extends Shape {
  final double width, height;
  Rectangle(this.width, this.height);
}
void analyzeShape(Shape shape) {
  switch (shape) {
    case Circle():           // Circle型として判別
      print('これは円です');
    case Rectangle():        // Rectangle型として判別  
      print('これは長方形です');
  }
}

void main() {
  analyzeShape(Circle(5));      // これは円です
  analyzeShape(Rectangle(4, 5)); // これは長方形です
}

クラスを判別対象として利用することも出来、その場合に継承元と先は区別される。

まとめ

whenというキーワードはこれまであまり見た記憶がなかったのでちょっと驚いた。
使い方がなんかifと被っているような気もするので、もうちょっとなんとかならんかったのだろうか?という思いがなくもない。
でもまぁ、そういう書き方もあるよというのは新しい言語を学ぶ中での楽しみでもあるので、この新しい書き方を楽しめるようになるしかないですな

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?