Initialize an array with a given value in Kotlin
This article explores different ways to initialize an array with a given value in Kotlin.
1. Using fill() function
The standard approach to initialize an array with some value in Kotlin is to use the extension function fill().
|
1 2 3 4 5 6 7 8 9 |
fun main() { val size = 5 val value = 1 val arr = arrayOfNulls<Int>(size) arr.fill(value) println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
2. Using Array Constructor
You can specify the array size using its constructor and initialize each element by calling a lambda. To initialize each element with a constant, you can do like:
|
1 2 3 4 5 6 7 8 |
fun main() { val size = 5 val value = 1 val arr = Array(size) { value } println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
3. Using Array class
Another solution is to use the setAll() function of the Arrays class, which uses a generator function that accepts an index and generates a value corresponding to that index.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.* fun main() { val size = 5 val value = 1 val arr = arrayOfNulls<Int>(size) Arrays.setAll(arr) { value } println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
4. Convert to List
In Kotlin, you can convert the array into a list and use the map() function to set a specific value for each list element by returning the same value for every index.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val size = 5 val value = 1 var arr = arrayOfNulls<Int>(size); arr = arr.toList().map { value }.toTypedArray() println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
5. Collections class
Alternatively, you can call Collections.nCopies() function to get a list initialized with a given value. Then copy the collection to a new array using the toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.* fun main() { val size = 5 val value = 1 val arr = Collections.nCopies(size, value).toTypedArray() println(arr.contentToString()) // [1, 1, 1, 1, 1] } |
That’s all about initializing an array with a given value in Kotlin.
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 :)