目錄

avoid_implementing_value_types

不要實作會覆寫 == 的類別。

此規則自 Dart 2.1 起可用。

詳細資訊

#

不要實作會覆寫 == 的類別。

== 運算子在合約上必須為等價關係;也就是說,對於所有物件 o1o2o1 == o2o2 == o1 必須同時為 true 或同時為 false。

注意:Dart 沒有真正的值類型,因此我們將實作 == 的類別視為識別值類型的代理

當使用 implements 時,您不會繼承 == 的方法主體,這使得幾乎不可能遵循 == 的合約。覆寫 == 的類別通常也可以直接在測試中使用,無需建立模擬或偽造物件。例如,對於給定的類別 Size

dart
class Size {
  final int inBytes;
  const Size(this.inBytes);

  @override
  bool operator ==(Object other) => other is Size && other.inBytes == inBytes;

  @override
  int get hashCode => inBytes.hashCode;
}

錯誤

dart
class CustomSize implements Size {
  final int inBytes;
  const CustomSize(this.inBytes);

  int get inKilobytes => inBytes ~/ 1000;
}

錯誤

dart
import 'package:test/test.dart';
import 'size.dart';

class FakeSize implements Size {
  int inBytes = 0;
}

void main() {
  test('should not throw on a size >1Kb', () {
    expect(() => someFunction(FakeSize()..inBytes = 1001), returnsNormally);
  });
}

正確

dart
class ExtendedSize extends Size {
  ExtendedSize(int inBytes) : super(inBytes);

  int get inKilobytes => inBytes ~/ 1000;
}

正確

dart
import 'package:test/test.dart';
import 'size.dart';

void main() {
  test('should not throw on a size >1Kb', () {
    expect(() => someFunction(Size(1001)), returnsNormally);
  });
}

用法

#

若要啟用 avoid_implementing_value_types 規則,請在您的 analysis_options.yaml 檔案中的 linter > rules 下新增 avoid_implementing_value_types

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_implementing_value_types