Kotlin List.asIterable() – Examples

Kotlin List.asIterable()


In Kotlin, the asIterable() function is used to convert a list into an iterable.

An iterable is a fundamental interface in Kotlin that represents a sequence of elements that can be iterated one at a time.

Syntax

List.asIterable()

Returns this List as an Iterable.

Example 1: Convert List to Iterable

In this example, we have to convert the given list to an iterable.

  1. Given a list of strings in myList.
  2. Call asIterable() function on myList, and store the returned iterable in myIterable.
  3. You may use a For loop to print the items in the iterable.

Program

fun main() {
    val myList = listOf("apple", "banana", "cherry")

    val myIterable = myList.asIterable()

    for(item in myIterable) {
        println(item)
    }
}

Output

apple
banana
cherry