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().

Download Code

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:

Download Code

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.

Download Code

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.

Download Code

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.

Download Code

That’s all about initializing an array with a given value in Kotlin.