How to initialize an array in Kotlin with values?
In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
How does Kotlin's array initialization look like?
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
See Kotlin - Basic Types for details.
You can also provide an initializer function as a second parameter:
val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]
Worth mentioning that when using kotlin builtines (e.g. intArrayOf()
, longArrayOf()
, arrayOf()
, etc) you are not able to initialize the array with default values (or all values to desired value) for a given size, instead you need to do initialize via calling according to class constructor.
// Array of integers of a size of N
val arr = IntArray(N)
// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
In Kotlin There are Several Ways.
var arr = IntArray(size) // construct with only size
Then simply initial value from users or from another collection or wherever you want.
var arr = IntArray(size){0} // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index
We also can create array with built in function like-
var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values
Another way
var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.
You also can use doubleArrayOf()
or DoubleArray()
or any primitive type instead of Int.
Here's an example:
fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3);
for (item in arr) {
println(item);
}
}
You can also use a playground to test language features.