英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论