Kotlin Array.flatten()

Kotlin Array.flatten() Tutorial

In Kotlin, the Array.flatten() function is used to flatten an array of arrays into a list. It simplifies the process of converting nested arrays into a flat list of elements.

This tutorial will explore the syntax of the Array.flatten() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.flatten() function is as follows:

fun <T> Array<out T>.flatten(): List<T>

The flatten() function returns a List.

Examples for Array.flatten() function

1. Flattening a 2D Array

In this example, we’ll use the flatten() function to flatten a 2D array into a single list of elements.

Kotlin Program

fun main() {
    val twoDArray = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9))

    // Using flatten() to flatten the 2D array
    val flatList = twoDArray.flatten()

    // Printing the original 2D array and the flattened list
    println("2D Array:\n[${twoDArray.map { it.contentToString() }.joinToString("\n")}]\n")
    println("Flattened List:\n$flatList")
}

Output

2D Array:
[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]]

Flattened List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Summary

In this tutorial, we’ve covered the flatten() function in Kotlin arrays, its syntax, and how to use it to convert an array of arrays into a list. This function is particularly useful when working with nested arrays, providing a concise way to flatten the structure and access individual elements.