メインコンテンツにスキップ

switch_on_type

安定版

'Type' に対する switch ステートメントを避けます。

詳細

#

Type による switch は避けてください

Type による switch は型安全ではなく、クラス階層が変更された場合にバグにつながる可能性があります。代わりに、変数に対するパターンマッチングを使用することを推奨します。

悪い例

dart
void f(Object o) {
  switch (o.runtimeType) {
    case int:
      print('int');
    case String:
      print('String');
  }
}

良い例

dart
void f(Object o) {
  switch(o) {
    case int():
      print('int');
    case String _:
      print('String');
    default:
      print('other');
  }
}

有効にする

#

switch_on_type ルールを有効にするには、analysis_options.yaml ファイルの linter > rules の下に switch_on_type を追加してください。

analysis_options.yaml
yaml
linter:
  rules:
    - switch_on_type

代わりに、linter ルールを設定するために YAML マップ構文を使用している場合は、linter > rules の下に switch_on_type: true を追加してください。

analysis_options.yaml
yaml
linter:
  rules:
    switch_on_type: true