This article explores different ways to create a list of fixed-size in Kotlin.

1. Using List constructor

The idea is to use the List constructor to create a list with the specified size, where each element is calculated by calling the specified function.

Download Code

Output:

[0, 0, 0, 0, 0]

 
To facilitate structural changes to the list, use the MutableList constructor. For instance,

Download Code

Output:

[0, 0, 0, 0]

2. Using map() function

Another option is to generate a sequentially ordered range of the required size and map it to some value. This can be done using the range operator and the map() function:

Download Code

Output:

[0, 0, 0, 0, 0]

 
The map() function returns a read-only list containing the results of applying the given transform function to each element. To add or remove elements from the list, convert the list into a mutable list.

Download Code

Output:

[0, 0, 0, 0]

3. Using Collections.nCopies() function

Alternatively, we can use the static function Collections.nCopies() to get an immutable list consisting of specified copies of the specified item.

Download Code

Output:

[0, 0, 0, 0, 0]

 
Don’t use this function on mutable objects, since the same instance of the object will be assigned to all indices. To add or remove elements from the list, convert the list into a mutable list.

Download Code

Output:

[0, 0, 0, 0]

4. Using arrayOfNulls() function

The arrayOfNulls() function returns an array of objects of the given type with the given size, initialized with nulls. To get a fixed-size list, pass the corresponding type array to the listOf() function, as shown below:

Download Code

Output:

[null, null, null, null, null]

 
To facilitate structural changes to the list, pass the corresponding type array to the mutableListOf() function. For instance,

Download Code

Output:

[null, null, null, null]

5. Using Array constructor

Another solution is to use the *Array constructor of the corresponding type *, which creates a new array of the specified size, with all elements initialized with the default value.

Download Code

Output:

[0, 0, 0, 0, 0]

 
To facilitate structural changes to the list, convert the corresponding type array to a mutable list with the toMutableList() function.

Download Code

Output:

[0, 0, 0, 0]

That’s all about creating a list of fixed-size in Kotlin.