This article explores different ways to initialize an IntArray with 1 to n in Kotlin.

1. Using IntArray constructor

A simple solution to initialize an Int array with a range of elements is using the IntArray constructor with an initializer function as a second parameter. This can be implemented as follows in Kotlin:

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2. Using Kotlin Ranges

Another viable alternative is to generate a range of increasing values is using the Kotlin Range. To get an IntArray, we can call the toIntArray() function, as shown below:

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 
To fill an “existing” array with an increasing sequence of numbers, do as follows:

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 
Or, even better:

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

3. Using Arrays.setAll() function

Finally, we can use the Arrays.setAll() function to fill the array with sequential integers. It takes the generator function and computes the value for each index, as shown below:

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

That’s all about initializing an IntArray with 1 to n in Kotlin.