F
F
foonfyrick2021-04-02 17:56:38
Kotlin
foonfyrick, 2021-04-02 17:56:38

When should you use an iterator? And is it used at all?

Well, I can go through the elements, I can find out if there is a next element, I can even go backwards in the listiterator, but for what? I can also use the for loop and go through the elements, and check if there is a next element.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-04-04
@foonfyrick

The for loop, all of a sudden, uses an iterator, it's just syntactic sugar to it. Also, a raw iterator can be useful if you need to change the list during iteration (for example, remove elements).
Also, for example, you can implement extensions like

val Fragment.parents: Iterable<Fragment>
Или
val ViewGroup.children: Iterable<View>
, which will allow, with the overhead of a couple of small objects, to conveniently work with entities that are not intended for iteration.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question