Kotlin Array associate()

Kotlin Array associate()

In Kotlin, the Array associate() function is used to create a Map by associating each element of this array with a key-value pair. It allows you to specify how to derive the keys and values from the elements of the array.

This function is useful when you want to transform an array into a Map where each element contributes to a specific key-value pair.

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

Syntax

The syntax of the associate() function is:

fun <T, K, V> Array<out T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>

where

ParameterDescription
transformA transformation function that defines how to create key-value pairs from the elements of the array.
Parameters of Array associate() function

The Array associate() function returns a Map containing the derived key-value pairs.

Examples for Array associate() function

1. Using associate() to Create a Map of Squares

In this example, we’ll use associate() to create a Map where each element of an array is associated with its square.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 4, 5)
    
    // Using associate to create a Map of squares
    val squareMap = numbersArray.associate { it to it * it }
    
    // Printing the original array and the resulting Map
    println("Original Numbers: ${numbersArray.joinToString(", ")}")
    println("Square Map: $squareMap")
}

Output

Original Numbers: 1, 2, 3, 4, 5
Square Map: {1=1, 2=4, 3=9, 4=16, 5=25}

2. Using associate() with a String Array

In this example, we’ll use associate() to create a Map where each word in a String array is associated with its length.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")
    
    // Using associate to create a Map of word lengths
    val wordLengthMap = wordsArray.associate { it to it.length }
    
    // Printing the original array and the resulting Map
    println("Original Words: ${wordsArray.joinToString(", ")}")
    println("Word Length Map: $wordLengthMap")
}

Output

Original Numbers: 1, 2, 3, 4, 5
Square Map: {1=1, 2=4, 3=9, 4=16, 5=25}

Summary

In this tutorial, we’ve covered the associate() function in Kotlin arrays, its syntax, and how to use it to create a Map by associating each element with a key-value pair. This function is valuable for transforming arrays into Maps with customized key-value relationships.