英文:
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<void> persist{final List<String>? 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<Type>
then it allows to reassign, modify and resize; withfinal
you can no longer reassign it and withconst
you can't change it at all. - A list can be set to
final
and the list content toconst
effectively making the listconst
. - 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 thatlist_a
will have the restrictions oflist_b
even if it hasvar
, 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 ['C', 'B', 'A'];
final list_b = list_a;
final list_c = list_a.toList(growable: false);
print('A == B: ${list_a == list_b}');
print('A == C: ${list_a == list_c}');
list_b.sort();
list_c.sort();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论