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 li
Old question, but if you'd like to use a range:
var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()
Yields nearly the same result as:
var numbers = Array(5, { i -> i*10 + 10 })
result: 10, 20, 30, 40, 50
I think the first option is a little more readable. Both work.
You can simply use the existing standard library methods as shown here:
val numbers = intArrayOf(10, 20, 30, 40, 50)
It might make sense to use a special constructor though:
val numbers2 = IntArray(5) { (it + 1) * 10 }
You pass a size and a lambda that describes how to init the values. Here's the documentation:
/**
* Creates a new array of the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns an array element given its index.
*/
public inline constructor(size: Int, init: (Int) -> Int)
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.
In Java an array can be initialized such as:
int numbers[] = new int[] {10, 20, 30, 40, 50}
But In Kotlin an array initialized many way such as:
Any generic type of array you can use arrayOf() function :
val arr = arrayOf(10, 20, 30, 40, 50)
val genericArray = arrayOf(10, "Stack", 30.00, 40, "Fifty")
Using utility functions of Kotlin an array can be initialized
val intArray = intArrayOf(10, 20, 30, 40, 50)
intialize array in this way : val paramValueList : Array<String?> = arrayOfNulls<String>(5)