Iterable interfaces

This is a parent interface in the interface hierarchy. Any data structure that contains a sequence of elements inherits from this interface. The Iterable interface provides an iterator, which is used to iterate over the elements. 

The Iterable interface contains only one function, which returns the iterator:

public interface Iterable<out T> {
public operator fun iterator(): Iterator<T>
}

To expose the interface to the list, it is necessary to define it in the declaration of the list:

val iterableValues : Iterable <Int> = listOf(1,2,3,4,5)

Now, the iterableValues variable can access the iterator to iterate over the list:

val iterator = iterableValues.iterator()

The Iterator interface provides two functions:

  • hasNext(): This functions returns true if the iterator finds the element in the list. Otherwise, it returns false.
  • next(): This function returns the element of the list.

Consider the following diagram. The list iterator provides the hasNext and next functions. If the hasNext function finds an element in the list, it returns true as a result, and the next function takes the element and moves the iterator to the next element:

The following code is an exact representation of the preceding diagram:

fun iterableWithListOfInt(){
val listOfInteger : Iterable<Int> = listOf(1,2,3,4,5)
val iterator = listOfInteger.iterator()
while (iterator.hasNext()) {
print(iterator.next())
}
}

The iterator iterates over the list and returns true if the hasNext function finds the element in the list. The next function returns the element and moves the iterator forward.

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

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