在Dart中允许对最终列表进行排序吗?

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

Is it allowed to sort a final list in Dart?

问题

以下是您要翻译的内容:

"有一个带有 final 参数的函数,即给定的 list 是不可变的。当我调用 list.sort() 时,IDE 中没有错误。sort 函数的返回类型是 void,也就是不需要创建新的引用。但是排序意味着改变内部的列表,也就是内存中的内部引用会发生变化,不是吗?

Future<void> persist(final List<String>? list) async {
  if (list != null) {
    list.sort(); // 在 IDE 中没有错误
    // ...
  }

  // ...
}
英文:

There is a function with final parameter i.e. the given list is final. There is no error in IDE when I call list.sort(). The sort function is a type of void i.e. it is not required to create a new reference. But sorting means changing the inner list i.e. the inner reference in memory will change, will not?

  Future&lt;void&gt; persist{final List&lt;String&gt;? list}) async {
    if (list != null) {
      list.sort(); // there is no error here in ide
      ...
    }

    ...
  }

答案1

得分: 1

是的,一个动态列表即使被标记为 final,仍然可以改变其内容,但这并不是列表唯一的限定符。它可以简化为以下几点:

  • 如果列表有 var 或者 <Type>,那么它可以被重新赋值、修改和调整大小;使用 final 将不能再次赋值,而使用 const 则完全无法改变它。
  • 一个列表可以被设置为 final,而列表中的内容可以被设置为 const,从而将整个列表变为 const
  • 动态列表可以使用 growable: false 创建,这样只限制了其大小,而不是内容的改变。
  • 使用 var list_a = list_b 只会复制引用,这意味着 list_a 会继承 list_b 的限制,即使它用了 var。要进行复制,需要使用 .toList() 成员函数。

如果出现错误,它将在运行时发生,因为 IDE 无法知道 list_b 最初是常量,就像类型转换错误一样无法被检测到。

英文:

Yes, a dynamic list can change its content even if it's marked as final, but it is not the only qualifier that a list can have, it can be simplified to:

  • If it has a var or &lt;Type&gt; then it allows to reassign, modify and resize; with final you can no longer reassign it and with const you can't change it at all.
  • A list can be set to final and the list content to const effectively making the list const.
  • Dynamic lists can be created with growable: false, this will only restrict the resizing and not the changing.
  • Using var list_a = list_b will only copy the reference, this measn that list_a will have the restrictions of list_b even if it has var, to make a copy you need to use the .toList() memeber.

If an error occurs, it will be at runtime as the ide can not see that list_b was originally constant in the same way that casting errors can't be detected.

final list_a = const [&#39;C&#39;, &#39;B&#39;, &#39;A&#39;];

final list_b = list_a;
final list_c = list_a.toList(growable: false);

print(&#39;A == B: ${list_a == list_b}&#39;);
print(&#39;A == C: ${list_a == list_c}&#39;);

list_b.sort();
list_c.sort();

huangapple
  • 本文由 发表于 2023年4月17日 17:51:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033824.html
匿名

发表评论

匿名网友

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

确定