This article explores different ways to initialize a list in Kotlin in a single line with the specified value.

There are several ways to initialize a list, as discussed below:

1. Using Collections.nCopies() function

The Collections.nCopies() function returns an immutable list of specified copies of the specified object.

Download Code

 
To get a mutable list, you can do like:

Download Code

2. Using map() function

Here, the idea is to get a range of indices for the list and transform the indices into the given value using the map() function.

Download Code

 
To get a mutable list, you can use the toMutableList() function.

Download Code

3. Using Array

Here, the idea is to create an array of the specified size and use the native fill() function to initialize it with a given value. Then use toList() function to get an immutable list.

Download Code

 
To get a mutable list, you can use the toMutableList() function.

Download Code

That’s all about initializing a list in Kotlin with the specified value.