Dart: Iterable vs. List, always use Iterable?

后端 未结 3 2033
你的背包
你的背包 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:55

    A List is an indexable collection of objects with a length.

    List class
    

    An iterable is a collection of values, or "elements", that can be accessed sequentially.

    Iterable class
    

    The elements of the iterable are accessed by getting an Iterator

    Iterator class
    

    Now, as you can see iterable does not have any add method. This is on purpose. We get following benefits from using iterable :

    • Using iterator we get a safer access to the list. Prevents accidental overriding of list as we get access to only one item at a time
    • Allows to keep the logic of modifying the list inside the class that contains it. Others can safely consume it.
    • This forces us to keep all complex operations related to the list inside its defining class

    Note : The Iterable and Iterator classes support for-in loops. Extend (if possible) or implement Iterable whenever you create a class that can provide Iterators for use in for-in loops. Implement Iterator to define the actual iteration ability.

提交回复
热议问题