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

case_expression_type_implements_equals

switch の case 式の型「{0}」では、`==` 演算子をオーバーライドできません。

説明

#

この診断は、case キーワードの後に続く式の型が、Object のもの以外の == 演算子の実装を持っている場合に、アナライザーによって生成されます。

#

以下のコードは、case キーワードの後に続く式 (C(0)) の型が C であり、クラス C== 演算子をオーバーライドしているため、この診断を生成します。

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  switch (c) {
    case C(0):
      break;
  }
}

一般的な修正

#

他に明確な理由がない限り、コードを if-else 構造を使用するように書き換えてください。

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  if (c == C(0)) {
    // ...
  }
}

switch 文を書き換えることができず、== の実装が不要な場合は、それ (== の実装) を削除してください。

dart
class C {
  final int value;

  const C(this.value);
}

void f(C c) {
  switch (c) {
    case C(0):
      break;
  }
}

switch 文を書き換えることができず、== の定義を削除することもできない場合は、switch を制御するために使用できる別の値を見つけてください。

dart
class C {
  final int value;

  const C(this.value);

  bool operator ==(Object other) {
    return false;
  }
}

void f(C c) {
  switch (c.value) {
    case 0:
      break;
  }
}