Kotlin arrayOf()

Kotlin arrayOf()

The Kotlin arrayOf() function is used to create an array with the specified elements.

Syntax

The syntax of arrayOf function is

fun <T> arrayOf(vararg elements: T): Array<T>

where

ParameterDescription
elementsThe elements to be included in the array.
Parameters of arrayOf() function

and T is the type of elements in the array.

Return Value

The function returns an Array type object containing the given elements.

Note: If no elements are passed to the arrayOf() function, then you need to specify the type of the elements in array after arrayOf and before the parenthesis.

arrayOf<T>()

For example, if you would like to create an empty array of integers, then you can use something like below.

arrayOf<Int>()

Example 1: Basic Usage of arrayOf()

In the following program, we create an array of integers using arrayOf() function. Call arrayOf() function and pass the integer values as arguments. We shall iterate over the returned array using a For loop, and print the array to output.

Kotlin Program

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)

    for (number in numbers) {
        println(number)
    }
}

Output

1
2
3
4
5

Example 2: Create Array with Mixed Data Types using arrayOf()

In this example, we shall create an Array with mixed data types: integers, strings, and characters.

Kotlin Program

fun main() {
    val mixedArray = arrayOf(1, "Hello", 'a', 3.14)

    for (element in mixedArray) {
        println(element)
    }
}

Output

1
Hello
a
3.14

This example demonstrates that an array can contain elements of different data types, such as integers, strings, characters, and floating-point numbers.

Example 3: Creating an Array of Custom Objects using arrayOf()

This example uses the arrayOf() function to create an array of custom objects (Person) and then prints each person in the array.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people = arrayOf(
        Person("Alice", 25),
        Person("Bob", 30),
        Person("Charlie", 22)
    )

    for (person in people) {
        println(person)
    }
}

Output

Person(name=Alice, age=25)
Person(name=Bob, age=30)
Person(name=Charlie, age=22)

Example 4: Creating an empty Array using arrayOf()

This example uses the arrayOf() function to create an empty array of strings and then checks if the array is empty.

Kotlin Program

fun main() {
    val emptyArray = arrayOf<String>()
    
    println("Is the array empty? ${emptyArray.isEmpty()}")
}

Output

Is the array empty? true

This example uses the arrayOf() function to create an empty array of strings and then checks if the array is empty.

Summary

In this tutorial, we have seen about Kotlin arrayOf() function, and how it allows us to easily initialize arrays with specific values or create empty arrays for later use. We have gone through the syntax, and well detailed examples covering different scenarios where we use arrayOf() function.