Kotlin Array.toList()

Kotlin Array.toList() Tutorial

The Array.toList() function in Kotlin is used to convert an Array to a List. It creates a new list containing the elements of the original array in the same order.

Array.toList() function is handy when you need to work with list-specific operations or interfaces in your Kotlin code.

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

Syntax

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

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

Examples for Array toList() function

1. Convert given array of integers to a list

In this example, we’ll take an array of integers in numbersArray, and use toList() to convert the given array of integers to a list of integers.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)

    // Using toList() to convert the array of integers to a list
    val numbersList = numbersArray.toList()

    // Printing the original array and the resulting list
    println("Numbers Array:\n${numbersArray.contentToString()}")
    println("Numbers List:\n$numbersList")
}

Output

Numbers Array:
[10, 20, 30, 40, 50]
Numbers List:
[10, 20, 30, 40, 50]

Summary

In this tutorial, we’ve covered the Array.toList() function in Kotlin arrays, its syntax, and how to use it to convert an array to a list.