Kotlin Array constructor

Kotlin Array Constructor

In Kotlin, arrays can be created using the Array class constructor. This constructor allows you to create an array of a specified size and initialize its elements using a lambda expression or a function.

In this tutorial, we’ll explore the syntax of the Kotlin Array constructor, how to use it to create arrays, and provide examples of different ways to initialize array elements.

Syntax

The syntax of the Kotlin Array constructor is as follows:

val arrayName = Array(size) { index -> elementValue }

where:

ParameterDescription
sizeThe size of the array, specifying the number of elements it should contain.
indexThe current index of the array element being initialized within the lambda expression or function.
elementValueThe value to be assigned to the array element at the current index.
Parameters of Kotlin Array Constructor

Examples for Kotlin Array Constructor

1. Creating an Array with Default Values

In this example, we’ll use the Kotlin Array constructor to create an array of integers with a specified size of 5, and all elements initialized to the default value for the element type (zero in this case).

Kotlin Program

fun main() {
    // Creating an array of size 5 with default values (0 for integers)
    val intArray = Array(5) { 0 }

    // Printing the array
    println("Integer Array\n${intArray.contentToString()}")
}

Output

Integer Array
[0, 0, 0, 0, 0]

2. Creating an Array with Indexed Values

In this example, we’ll use the Kotlin Array constructor to create an array of strings with a specified size of 4, where each element is initialized to a string containing its index.

Kotlin Program

fun main() {
    // Creating an array of size 4 with elements initialized to their indices as strings
    val stringArray = Array(4) { index -> "Element $index" }

    // Printing the array
    println("String Array\n${stringArray.contentToString()}")
}

Output

String Array
[Element 0, Element 1, Element 2, Element 3]

Summary

In this tutorial, we’ve covered the Kotlin Array constructor, its syntax, and how to use it to create arrays with specified sizes and initial values.