为什么在Dart中覆盖某些字段时需要将类标记为不可变?

huangapple go评论51阅读模式
英文:

Why do we have to annotate a class as immutable when overriding certain fields in dart?

问题

为什么在Dart中我们必须为覆盖hashCode==运算符的类添加@immutable注释?例如:

@immutable
class RandomClass {
  final Object identifier;

  const RandomClass({
    required this.identifier,
  });

  @override
  bool operator ==(Object other) {
    if (other is RandomClass) {
      return other.identifier == identifier;
    }
    return false;
  }

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

当我不将RandomClass标记为不可变时,会给我一个警告,因为我覆盖了==运算符。

我理解在将类标记为不可变时的影响,但我想知道为什么在某些情况下我们必须这样做,即当一个类覆盖特定字段时。

英文:

Why do we have to annotate a class the overrides hashCode and the == operator in dart as immutable? For example:

@immutable
class RandomClass {
  final Object identifier;

  const RandomClass({
    required this.identifier,
  });

  @override
  bool operator ==(Object other) {
    if (other is RandomClass) {
      return other.identifier == identifier;
    }
    return false;
  }

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

Gives me a warning when I don't annotate RandomClass as immutable because I override the == operator

I understand the effects of marking a class as immutable, but am wondering why we have to do that when a class overrides certain fields.

答案1

得分: 0

根据有效的Dart文档(感谢@jamesdlin提供链接)。
> 当您定义==时,您还必须定义hashCode。这两者都应考虑到对象的字段。如果这些字段发生更改,那就意味着对象的哈希码也会发生更改。
>
> 大多数基于哈希的集合不会预见到这一点 - 他们假设对象的哈希码将永远相同,并且如果这不成立,则可能会表现出不可预测的行为。

英文:

According to the effective dart docs (thanks to @jamesdlin for linking to it).
> When you define ==, you also have to define hashCode. Both of those should take into account the object’s fields. If those fields change then that implies the object’s hash code can change.
>
> Most hash-based collections don’t anticipate that—they assume an
> object’s hash code will be the same forever and may behave
> unpredictably if that isn’t true.

huangapple
  • 本文由 发表于 2023年5月25日 01:33:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326092.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定