This post will discuss how to declare and initialize an array in Kotlin with a specific value.

1. Using arrayOf() function

To create an Array in Kotlin, you can use the library function arrayOf() and pass the desired values to it. This is demonstrated below:

Download Code

2. Using Array Constructor

Another option is to use the Array constructor, which takes the array size and the function that can return the initial value of each array element given its index.

The following code creates an Array of Int of size 5 with all values initialized with a constant.

Download Code

 
To create an array with values initialized to their index value, you can use the following code:

Download Code

3. Primitive type arrays

Kotlin offers specialized classes to represent arrays of primitive types such as IntArray, DoubleArray, LongArray, etc. To initialize primitive arrays with a specific value, you can use the class constructor with lambda.

For example, IntArray(5) creates an integer array of size 5 and initializes it with a value of 1.

Download Code

 
Alternatively, you can create primitive type array in Kotlin with desired values using factory function intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), etc.

Download Code

4. Using arrayOfNulls() function

The arrayOfNulls() function returns an array of objects of the given type with the given size, initialized with null values.

Download Code

5. Using emptyArray() function

Kotlin allows having arrays of size 0 using the emptyArray() function. Since it’s an empty array, it throws an ArrayIndexOutOfBoundsException if you try to read or assign elements.

Download Code

That’s all about declaring and initializing an array in Kotlin.

 
Reference: Basic Types: Numbers, Strings, Arrays – Kotlin Programming Language