In this tutorial, you shall learn how to create an array in Kotlin using arrayOf() function, with examples.

Kotlin – Create an Array

To create an Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.

Syntax

The syntax to create an Array of type T is

arrayOf<T>(value1, value2, ...)

where value1, value2, and so on are of type T. For example T can be Int, String, Byte, etc.

Kotlin can infer the type of Array from the argument values. Therefore, we can create an array with initial values as shown in the following.

arrayOf(value1, value2, ...)

If no values are passed to arrayOf() function, then we must specify the datatype T as shown in the following.

arrayOf<T>()
ADVERTISEMENT

Examples

1. Create an array of integers

In the following program, we create an Integer array with four initial elements.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf(2, 4, 6, 8)
    for (x in arr) print("$x ")
}

Output

2 4 6 8

2. Create an array of byte objects

In the following program, we create a Byte Array with four initial elements.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf<Byte>(25, 41, 85, 3)
    for (x in arr) print("$x ")
}

Output

25 41 85 3

3. Create an array of strings

In the following program, we create a String Array with three initial elements.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    for (x in arr) print("$x ")
}

Output

apple banana cherry

Conclusion

In this Kotlin Tutorial, we learned how to create an Array using arrayOf() function, with examples.