Kotlin Array asIterable()

Kotlin Array asIterable()

In Kotlin, the asIterable() function is used to convert an array into an iterable. It allows you to work with arrays using the functions and features provided by the Iterable interface.

This function is helpful when you need to treat an array as an iterable, enabling the use of operations like map, filter, and others available for iterables.

In this tutorial, we’ll explore the syntax of the asIterable() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the asIterable() function is:

fun <T> Array<out T>.asIterable(): Iterable<T>

Examples

1. Using asIterable() for Iteration

In this example, we’ll use Array asIterable() function to convert an array of numeric values, numbersArray, into an iterable and perform iteration operations.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(100, 200, 300, 400, 500)

    // Converting array to iterable using asIterable
    val numbersIterable: Iterable<Int> = numbersArray.asIterable()

    // Using iterable operations
    val doubledNumbers = numbersIterable.map { it * 2 }

    // Printing the original array and the result
    println("Original Array: ${numbersArray.joinToString(", ")}")
    println("Doubled Numbers: ${doubledNumbers.joinToString(", ")}")
}

Output

Original Array: 100, 200, 300, 400, 500
Doubled Numbers: 200, 400, 600, 800, 1000

In this example, we use asIterable() to convert an array of numbers into an iterable. We then use the iterable operations, such as map, to double each number. The original array and the result are printed to the console.

2. Using asIterable() for Filtering

In this example, we’ll use asIterable() to convert an array into an iterable and perform filtering based on a condition.

Kotlin Program

fun main() {
    val temperaturesArray = arrayOf(22, 25, 18, 30, 15)
    
    // Converting array to iterable using asIterable
    val temperaturesIterable: Iterable<Int> = temperaturesArray.asIterable()
    
    // Using iterable operations to filter temperatures above 20 degrees
    val warmTemperatures = temperaturesIterable.filter { it > 20 }
    
    // Printing the original array and the result
    println("Original Temperatures: ${temperaturesArray.joinToString(", ")}")
    println("Warm Temperatures: ${warmTemperatures.joinToString(", ")}")
}

Output

Original Temperatures: 22, 25, 18, 30, 15
Warm Temperatures: 22, 25, 30

In this example, we use asIterable() to convert an array of temperatures into an iterable. We then use the iterable operation filter to retain only the temperatures above 20 degrees. The original array and the filtered result are printed to the console.

Summary

In this tutorial, we’ve covered the asIterable() function in Kotlin arrays, its syntax, and how to use it to convert an array into an iterable.