Declare and initialize an array in Kotlin
This post will discuss how to declare and initialize an array in Kotlin with a specific value.
1. Using arrayOf() function
To create an Array in Kotlin, you can use the library function arrayOf() and pass the desired values to it. This is demonstrated below:
|
1 2 3 4 |
fun main() { val arr = arrayOf(1, 2, 3, 4, 5) println(arr.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using Array Constructor
Another option is to use the Array constructor, which takes the array size and the function that can return the initial value of each array element given its index.
The following code creates an Array of Int of size 5 with all values initialized with a constant.
|
1 2 3 4 5 |
fun main() { val arr = Array(5) { 1 } println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
To create an array with values initialized to their index value, you can use the following code:
|
1 2 3 4 5 |
fun main() { val arr = Array(5) { it } println(arr.contentToString()) // [0, 1, 2, 3, 4] } |
3. Primitive type arrays
Kotlin offers specialized classes to represent arrays of primitive types such as IntArray, DoubleArray, LongArray, etc. To initialize primitive arrays with a specific value, you can use the class constructor with lambda.
For example, IntArray(5) creates an integer array of size 5 and initializes it with a value of 1.
|
1 2 3 4 5 |
fun main() { val arr = IntArray(5) { 1 } println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
Alternatively, you can create primitive type array in Kotlin with desired values using factory function intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), etc.
|
1 2 3 |
fun main() { val arr: IntArray = intArrayOf(1, 2, 3, 4, 5) } |
4. Using arrayOfNulls() function
The arrayOfNulls() function returns an array of objects of the given type with the given size, initialized with null values.
|
1 2 3 4 5 |
fun main() { val arr = arrayOfNulls<Int>(5) println(arr.contentToString()) // [null, null, null, null, null] } |
5. Using emptyArray() function
Kotlin allows having arrays of size 0 using the emptyArray() function. Since it’s an empty array, it throws an ArrayIndexOutOfBoundsException if you try to read or assign elements.
|
1 2 3 4 |
fun main() { val arr = emptyArray<Int>() println(arr.contentToString()) // [] } |
That’s all about declaring and initializing an array in Kotlin.
Reference: Basic Types: Numbers, Strings, Arrays – Kotlin Programming Language
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)