Dart:可迭代E。与List< E>总是使用Iterable吗? [英] Dart: Iterable<E> vs. List<E>, always use Iterable?
问题描述
Dart新手问题。
Dart newbie question.
List是Iterable的子类,某些列表方法返回Iterable而不是List,例如List的 where方法。如果我们将变量声明为List,则必须在许多地方调用 toList
。
List is a child class of Iterable, and some list methods return Iterable instead of List, e.g., List's where method. If we declare a variable as List, we have to call toList
in many places.
总是更好声明我们的变量为Iterable类型而不是List(或任何其他子类型),那么我们的代码是通用的并且易于更改?这样做有什么缺点吗?这更像是一个最佳实践问题。
Is it better to always declare our variable as Iterable type instead of List (or any other subtypes), so our code is generic and easy to change? Is there any downside of doing so? This is more like a best practice question.
编辑
在我的代码库中将某些列表更改为Iterable之后,我发现Iterable实例没有 add
方法。顾名思义,它过去仅是 item 。如此明显。
After changing some List to Iterable in my codebase, I found Iterable instances have no add
method. It is used to be iterated only, as the name suggests. So obvious.
推荐答案
您应将变量声明为提供功能并保证所需的最精确类型。
You should declare your variables as the most precise type that provides the functionality and guarantees that you need.
列表保证有效的长度和随机访问操作,并提供对 sort
和 shuffle之类的功能的访问
仅在从一开始就可以访问所有元素时才有效。它们属于 List
,因为如果它们位于 Iterable
上,则每个有效的实现都将以 toList
仍然可以获得列表。
List guarantees efficient length and random access operations, and gives access to functionality like sort
and shuffle
which are only efficient when they have access to all the elements from the start. They belong on List
because if they had been on Iterable
, every efficient implementation would start by doing toList
to get a list anyway.
您应该对代码有相同的看法:如果您希望或期望有一个列表,请键入它作为列表
。如果可以处理任何集合,请使用 Iterable
-这通常意味着您可以使用 for-in $实现所有操作c $ c>在元素上。
如果您始终要在使用之前将其转换为列表,则最好将变量键入 List
以确保您记得
You should think the same way about your code: If you want or expect a list, type it as List
. If you can do with any collection, use Iterable
- which usually means that the operations you use can all be implemented by a for-in
over the elements.
if you are always going to transform an iterable into a list before you use it, you might as well type the variable as List
to make sure you remember to make the list.
或者简而言之,如果您不在乎它实际上是 Set
还是队列
或 LinkedList
,或者它是不可修改的还是惰性的,都可以将其设为可迭代
。
Or, in short, if you don't care whether it's actually a Set
or Queue
or LinkedList
or whether it's unmodifiable or lazy, you can make it an Iterable
.
(通常,您应该只迭代一次可迭代的对象-当您想使用两次时,可能从中创建一个保证非延迟的集合-并且 List
是最便宜的集合)。
(You should still generally only iterate an iterable once - the moment you want to use it twice, it's likely that you'd be better off creating a guaranteed non-lazy collection from it - and List
is the cheapest collection to create).
这篇关于Dart:可迭代E。与List< E>总是使用Iterable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!