Kotlin Array - flatten() Function



The Kotlin array flatten() function is used to create a single list by merging all sub-arrays and returns a list of all elements from all arrays in the given array.

For example, if we have an array of arrays like arrayOf(arrayOf(1), arrayOf(2, 3)) and we call flatten() on it, the resulting list will be [1, 2, 3].

Syntax

Following is the syntax of Kotlin array flatten() function −

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

Parameters

This function does not accepts any parameters

Return value

This function returns a new list containing all the elements of the sub-array.

Example 1

Following is the basic example to demonstrate the use of flatten() function −

fun main(args: Array<String>){
   val deepArray = arrayOf(
      arrayOf(1),
      arrayOf(2, 3),
      arrayOf(4, 5, 6)
   )
   // use the flatten function
   val list = deepArray.flatten()
   println("list: $list")
}

Output

On execution of the above code we get the following result −

list: [1, 2, 3, 4, 5, 6]

Example 2

Now, let's see another example. Here, we use the flatten() function to return a list containing all sub array −

fun main(args: Array<String>){
   val deepArray = arrayOf(
      arrayOf("tutorialspoint"),
      arrayOf("tut", "tutorix"),
      arrayOf("Hyd", "Hyderabad", "India")
   )
   val list = deepArray.flatten()
   println("list: $list")
}

Output

After execution of the above code we get the following output −

list: [tutorialspoint, tut, tutorix, Hyd, Hyderabad, India]

Example 3

The following example creates a list from a sub-array that contains both characters and strings −

fun main(args: Array<String>){
   val deepArray = arrayOf(
      arrayOf("Name:"),
      arrayOf('D', 'a'),
      arrayOf('i', 's', 'y')
   )
   val list = deepArray.flatten()
   println("list: $list")
}

Output

The above code produce following output −

list: [Name:, D, a, i, s, y]
kotlin_arrays.htm
Advertisements