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?

Javaから見たDartのswitch文の相違点

Posted at

主な違いまとめ

  • すべての型に対応
  • Dartはbreak;がなくてもcaseを抜ける
  • パターンマッチ対応
  • nullに対応

Dartは break; がなくても case を抜ける

Javaではbreak;がないとその後に続くcaseも逐次実行していたが(フォールスルー)
Dartではcaseごとに処理を終了する。

String color = "red";

switch (color) {
  case "red":
    System.out.println("赤です");
  case "blue":
    System.out.println("青です");
    break;
  default:
    System.out.println("その他の色");
}
赤です
青です
String color = 'red';

switch (color) {
  case 'red':
    print('赤です');
  case 'blue':
    print('青です');
  default:
    print('その他の色');
}
赤です

パターンマッチ対応

Javaでも17〜21で一部対応しているらしいが
型チェックが可能
またwhenで分岐が可能

Object value = 42;

switch (value) {
  case int n when n.isEven:
    print('偶数: $n');
  case int n:
    print('奇数: $n');
  case String s:
    print('文字列: $s');
  default:
    print('不明な型');
}
偶数: 42

nullに対応

Javaだとヌルポを投げていたが
Dartだとcase nullで対応可能

String? color = null;

switch (color) {
  case 'red':
    print('赤です');
  case null:
    print('null です');
  default:
    print('その他の色');
}
null です

おわりに

Javaで感じていた不便な部分や、直感的でない部分などがDartでは修正されていて驚きました。
また内容等に不出来がありましたらコメントください。

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?