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 as List, we have to call toList
in many places.
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.
Edits
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.
Iterable is an extract class, it can't de instantiate directly. The difference with List and Iterable is that that element in the list can be accessed with their index value using [] operator while in Iterable value can't be accessed using [] operator. If we run the above program. We get the operator error.
Both List and Set are Iterable , so they have the same methods and properties as the Iterable class.
A List is completely concrete at its inception. An Iterable is a "lazy list", and might even be an infinite list. Iterables are computed as needed. They have similar properties, but different realizations.
A List implements the Iterable interface. An Iterator allows you to iterate through a List 's elements.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With