Kotlin Tutorials

Kotlin Set asIterable()
Syntax & Examples

Set.asIterable() extension function

The asIterable() extension function for sets in Kotlin returns the set itself as an Iterable, allowing for use in contexts that require an Iterable.


Syntax of Set.asIterable()

The syntax of Set.asIterable() extension function is:

fun <T> Set<T>.asIterable(): Iterable<T>

This asIterable() extension function of Set returns this set as an Iterable.

Return Type

Set.asIterable() returns value of type Iterable.



✐ Examples

1 Using asIterable() to treat a set as an Iterable

In Kotlin, we can use the asIterable() function to treat a set as an Iterable.

For example,

  1. Create a set of integers.
  2. Use the asIterable() function to get an Iterable from the set.
  3. Iterate over the elements of the Iterable using a for loop and print each element to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5)
    val iterable: Iterable<Int> = numbers.asIterable()
    for (number in iterable) {
        println(number)
    }
}

Output

1
2
3
4
5

2 Using asIterable() with a set of strings

In Kotlin, we can use the asIterable() function to treat a set of strings as an Iterable.

For example,

  1. Create a set of strings.
  2. Use the asIterable() function to get an Iterable from the set.
  3. Iterate over the elements of the Iterable using a for loop and print each element to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry")
    val iterable: Iterable<String> = fruits.asIterable()
    for (fruit in iterable) {
        println(fruit)
    }
}

Output

apple
banana
cherry

3 Using asIterable() with an empty set

In Kotlin, we can use the asIterable() function to treat an empty set as an Iterable.

For example,

  1. Create an empty set of integers.
  2. Use the asIterable() function to get an Iterable from the empty set.
  3. Iterate over the elements of the Iterable using a for loop and print each element to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val iterable: Iterable<Int> = emptySet.asIterable()
    for (number in iterable) {
        println(number)
    }
}

Output


Summary

In this Kotlin tutorial, we learned about asIterable() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.