How to Initialize Array in Kotlin With Values

Kailash Vaviya Feb 02, 2024
  1. Declare an Array in Kotlin
  2. Use the arrayOf() Function to Declare and Initialize an Array in Kotlin
  3. Declare and Initialize an Array in Kotlin With the Array Constructor
  4. Declare and Initialize Array Values in Kotlin Using Primitive Types
  5. Declare and Initialize Array in Kotlin With arrayOfNulls() Function
  6. Declare and Initialize Array in Kotlin With the fill() Function
  7. Declare and Initialize Array Values in Kotlin From a Range
How to Initialize Array in Kotlin With Values

This tutorial will teach us to initialize an array in Kotlin with values.

Using different ways, such as arrayOf(), array constructor, primitive types, arrayOfNulls(), fill(), and from a range.

Declare an Array in Kotlin

An array stores multiple items together for easy sorting and searching through a collection of elements.

All the items stored in a Kotlin array are called elements that can be accessed with the help of their index numbers starting from 0.

Declare an array in Kotlin in two ways:

  • Using the arrayOf() function and array constructor.
  • Initialize an array with values while declaring it.

Use the arrayOf() Function to Declare and Initialize an Array in Kotlin

Create an array with the help of the library function arrayOf() and initialize it with any values we want.

There are two ways to do this: implicit and explicit types.

We can use the arrayOf() function and start initializing the implicit declaration values. But for the explicit declaration, we can control the input in the array by explicitly declaring a data type.

In the below example, we will create an array Student using implicit declaration and initialize it with students' names.

fun main() {
    val Student = arrayOf("Mark", "Anthony", 3, true)
    println (Student.contentToString())
}

Output:

[Mark, Anthony, 3, true]

The implicit declaration accepts any data type and converts it to String while compiling. But if we use explicit declaration, the program will only accept a String and throw an error for any other data types.

fun main() {
    val Student = arrayOf<String>("Mark", "Anthony", 3, true)
    println (Student.contentToString())
}

Output:

! The integer literal does not conform to the expected type String
! The boolean literal does not conform to the expected type String

However, initializing the array only with String values will run as expected.

Declare and Initialize an Array in Kotlin With the Array Constructor

It requires two parameters: size and a function to calculate value.

Syntax:

val array_name = Array (size, {value_function})

Using this syntax, we will create and initialize an array in Kotlin.

fun main()
{
    val array_example = Array(3, { n -> n * 1 + 3 })
    for (n in 0..array_example.size-1)
    {
        println(array_example[n])
    }
}

Output:

3 4 5

We can also replace the function with a single value or it. If we replace it with a single value, the array will be initialized in all the indexes.

On the other hand, if we use it, we will initialize the array with the respective indexes. The it keyword refers to the indexes of items.

Hence, we can also eliminate the for in the above code by using the it keyword.

fun main()
{
    val array_example = Array(3, { it -> it * 1 + 3 })
		println(array_example.contentToString())
}

Output:

[3, 4, 5]

Declare and Initialize Array Values in Kotlin Using Primitive Types

Kotlin allows creating primitive type arrays using the functions intArrayOf(), charArrayOf(), doubleArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), and byteArrayOf().

Compiling the arrays created using these functions will reflect as int[], char[], etc.

fun main()
{
    val arr = charArrayOf('a', 'b', 'c', 'd')
    print(arr)
}

Output:

abcd

Declare and Initialize Array in Kotlin With arrayOfNulls() Function

The arrayofNulls() function will declare the mentioned size and type array and fill it with null values.

We will use the arrayofNulls() function to create an array of size 3 and null values in the code below.

fun main() {
    val array_example = arrayOfNulls<String>(3)
    println(array_example.contentToString())
}

Output:

[null, null, null]

Similarly, we can create an empty array with the emptyArray() function. We don’t need to provide any arguments to the emptyArray() function as it will simply create an empty one without any data in it.

Declare and Initialize Array in Kotlin With the fill() Function

The fill() function will initialize the array in Kotlin with the given value. However, this requires declaring variables to hold the values for size and items to later initialize the array.

fun main() {
    val s = 3
    val v = 5

    val array_example = arrayOfNulls<Int>(s)
    array_example.fill(v)

    println(array_example.contentToString())
}

Output:

[5, 5, 5]

Declare and Initialize Array Values in Kotlin From a Range

We need to convert the range to a list with the toList() function and add the individual values to the array from a given range. But for this to work, we need to import the Java Array package.

import java.util.Arrays
fun main() {
    val array_example = (4..9).toList().toTypedArray()
    println(Arrays.toString(array_example))
}

Output:

[4, 5, 6, 7, 8, 9]
Kailash Vaviya avatar Kailash Vaviya avatar

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.

LinkedIn

Related Article - Kotlin Array