In this tutorial, you shall learn how to create an array of Integer objects in Kotlin using arrayOf() function, with examples.
Kotlin – Create Integer Array
To create an integer 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 Int
is
arrayOf<Int>(value1, value2, ...)
where value1, value2, and so on are the integer values.
Kotlin can infer the type of Array from the argument values. Therefore, we can create a Int array with initial integer values as shown in the following.
arrayOf(value1, value2, ...)
If no values are passed to arrayOf() function, then we must specify the datatype Int as shown in the following.
arrayOf<Int>()
Examples
1. Create an integer array with four elements
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
Conclusion
In this Kotlin Tutorial, we learned how to create an Integer Array using arrayOf() function, with examples.