In this article we will discuss about array declarations and initialization. In kotlin we have savers way to define and initialize array like arrayOf() function, using array constructor, using arrayOfNulls() function, using emptyArray() function. Let’s understand about all these functions and there functionality.
- By the use of arrayOf() function
In kotlin while creating array you can use arrayOf() function and you can assign value ot it like
fun main() {
val arr = arrayOf(1, 2, 3, 4, 5)
println(arr.contentToString()) // [1, 2, 3, 4, 5]
}
- By the use of Array Constructor
You can also create array in kotlin using Array constructor, which takes the array size and a function which accepts the index of a given element and returns the initial value of that element.
Here is the example of creating array of Int type will value of size 5.
fun main() {
val arr = Array(5) { 1 }
println(arr.contentToString()) // [1, 1, 1, 1, 1]
}
To create an array with values at their index value, you can try this code:
fun main() {
val arr = Array(5) { it }
println(arr.contentToString()) // [0, 1, 2, 3, 4]
}
- Primitive type arrays
Kotlin provide us specialized classes which help us to represent arrays of primitive types like IntArray, DoubleArray, LongArray, etc. For declare and initialize primitive arrays with a specific type of value, you must use the class constructor with lambda.
Here is the example of creating array of Int type will value of size 5.
fun main() {
val arr = IntArray(5) { 1 }
println(arr.contentToString()) // [1, 1, 1, 1, 1]
}
Also, you can create array of primitive type in Kotlin with desired values with the use of factory function like charArrayOf(), longArrayOf(), intArrayOf(), booleanArrayOf(), etc.
fun main() {
val arr: IntArray = intArrayOf(11, 22, 33, 44, 55)
}
- Using arrayOfNulls() function
This arrayOfNulls() function returns an array with null value of the given type with the given size.
fun main() {
val arr = arrayOfNulls(5)
println(arr.contentToString()) // [null, null, null, null, null]
}
- Using emptyArray() function
In kotlin you can also create arrays of 0 size using the emptyArray() function. If you try to read or reassign value to it then it will throws an ArrayIndexOutOfBoundsException it’s an empty array,.
fun main() {
val arr = emptyArray()
println(arr.contentToString()) // []
}