Kotlin Array.zip()

Kotlin Array.zip() function

In Kotlin, the Array.zip() function is used to combine the elements of two arrays into pairs. It returns a new list of pairs, where each pair consists of elements from the corresponding positions in the input arrays. If the arrays have different sizes, the result will have the size of the smaller array.

This function is particularly useful when you need to iterate over multiple arrays simultaneously or create pairs of elements from two different sources.

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

Syntax

The syntax of the zip() function is:

fun <T, R> Array<out T>.zip(
    other: Array<out R>,
): List<Pair<T, R>>

The zip() function is called on an array and takes other array as argument. The function returns a list of pairs, where the first element of each pair is from the calling array, and the second element from the array is from the argument array.

Examples for Array.zip() function

1. Combining Arrays into Pairs

In this example, we’ll use zip() to combine elements from two arrays into pairs.

Kotlin Program

fun main() {
    val namesArray = arrayOf("Alice", "Bob", "Charlie")
    val agesArray = arrayOf(25, 30, 22)

    // Combining arrays into pairs
    val nameAgePairs = namesArray.zip(agesArray)

    // Printing the result
    println("Name-Age Pairs\n$nameAgePairs")
}

Output

Name-Age Pairs
[(Alice, 25), (Bob, 30), (Charlie, 22)]

Summary

In this tutorial, we’ve covered the Array.zip() function in Kotlin, its syntax, and how to use it to combine elements from two arrays into pairs.