Improve iterator samples, add explanatory comments (KT-20357)
This commit is contained in:
@@ -29,6 +29,7 @@ class Iterators {
|
||||
add("BLUE")
|
||||
}
|
||||
|
||||
// iterator() extension is called here
|
||||
for (e in vector.elements()) {
|
||||
println("The element is $e")
|
||||
}
|
||||
@@ -39,12 +40,14 @@ class Iterators {
|
||||
val mutableList = mutableListOf(1, 2, 3)
|
||||
val mutableIterator = mutableList.iterator()
|
||||
|
||||
if (mutableIterator.hasNext()) {
|
||||
mutableIterator.next()
|
||||
mutableIterator.remove()
|
||||
}
|
||||
|
||||
// iterator() extension is called here
|
||||
for (e in mutableIterator) {
|
||||
if (e % 2 == 0) {
|
||||
// we can remove items from the iterator without getting ConcurrentModificationException
|
||||
// because it's the same iterator that is iterated with for loop
|
||||
mutableIterator.remove()
|
||||
}
|
||||
|
||||
println("The element is $e")
|
||||
}
|
||||
}
|
||||
@@ -61,10 +64,12 @@ class Iterators {
|
||||
@Sample
|
||||
fun forEachIterator() {
|
||||
val iterator = (1..3).iterator()
|
||||
// skip an element
|
||||
if (iterator.hasNext()) {
|
||||
iterator.next()
|
||||
}
|
||||
|
||||
// do something with the rest of elements
|
||||
iterator.forEach {
|
||||
println("The element is $it")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user