for loops

A for loop statement allows us to iterate anything that contains the iterate() method. In turn, this provides an instance that matches the iterator interface through the principle of duck typing.

The duck typing principle means that an interface is implemented implicitly if all of the methods that it contains are implemented.

The Iterator interface looks as follows:

public interface Iterator<E> {

boolean hasNext();

E next();
}

If we want to provide the iterator(), hasNext(), and next() methods as class members, we have to declare them with the operator keyword. The following example demonstrates a case of this:

class Numbers(val numbers: Array<Int>) {

private var currentIndex: Int = 0

operator fun iterator(): Numbers = Numbers(numbers)

operator fun hasNext(): Boolean = currentIndex < numbers.lastIndex

operator fun next(): Int = numbers[currentIndex ++]
}

The Numbers class can be used as follows:

fun testForLoop() {
val numbers = Numbers(arrayOf(1, 2, 3))
for (item in numbers) {
//......
}
}

An implementation using extension functions is as follows:

class Numbers(val numbers: Array<Int>)

private var currentIndex = 0
operator fun Numbers.iterator(): Numbers {
currentIndex = 0
return this
}
operator fun Numbers.hasNext(): Boolean = currentIndex < numbers.lastIndex
operator fun Numbers.next(): Int = numbers[currentIndex ++]

As you can see, extension functions allow us to make preexisting classes iterable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.126.199