Dart: Iterable vs. List, always use Iterable?

后端 未结 3 2038
你的背包
你的背包 2020-12-30 23:28

Dart newbie question.

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

3条回答
  •  一个人的身影
    2020-12-30 23:57

    You should declare your variables as the most precise type that provides the functionality and guarantees that you need.

    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.

    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.

    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.

    (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).

提交回复
热议问题