How to create a mutable list with repeating elements in Kotlin?


A Mutable List is an interface and generic collection of elements. Once a collection is declared as mutable, it becomes dynamic and we can modify its data as per requirement. A mutable list grows automatically in size as we insert new elements into it. The Mutable List inherits form the Generic<T> class.

Example – Creating a Mutable List in Kotlin

In order to create a mutable list of repeating elements, we will be using Kotlin List(). By definition, it looks like this−

inline fun <T> List(
   size: Int,
   init: (index: Int) -> T
): List<T>

As we pass an initial default value, it creates a read only list of specified number of elements. In this List(), each element is calculated by calling the specified init function.

In this example, we will be using a Mutable List to create a list of the squares of the first 5 numbers.

fun main(args: Array<String>) {
   val squares = MutableList(5) { (it + 1) * (it + 1) }

   // printing the squares of first 5 elements
   println(squares)
}

Output

It will produce the following output −

[1, 4, 9, 16, 25]

Example – Creating a Mutable List with Repeating Elements in Kotlin

In order to create a dummy mutable list, we can just modify the above piece of code with a dummy String. As a result, we will be getting a mutable list of repeating elements.

fun main(args: Array<String>) {
   val squares = MutableList(5) {"Dummy"}
   println(squares)
}

Output

On execution, it will produce the following output −

[Dummy, Dummy, Dummy, Dummy, Dummy]

Updated on: 16-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements