1. Overview

In this quick tutorial, we’re going to learn how to create collections with repeating elements in them.

2. Creating Repeating Collections

As of Kotlin 1.1, we can use the List(size: Int, init: (index: Int) -> T) function to create a read-only list with the specified size. Additionally, we can initialize each element with the given init function, which takes the element position as the input:

val repeated = List(3) { index -> "Hello" }

Here, we’re creating a List with three elements, all equal to “hello”. Since we don’t use the lambda argument, we can also replace it with the underscore character:

val repeated = List(3) { _ -> "Hello" }

And even more concisely, we can even drop the underscore:

val repeated = List(3) { "Hello" }

This way, we’re defaulting to the “it” lambda argument name but we’re never using it. Similarly, we can use the same approach for other types of collections such as MutableList or different types of arrays:

val mutable = MutableList(3) { "Hello" }

val charArray = CharArray(3) { 'H' }

val array = Array(3) { "Hello" }

val intArray = IntArray(3) { 42 }

In addition to this, we can create a sequence with the same element repeated using the generateSequence(nextFunction: () -> T?) function:

val repeated = generateSequence { "Hello" }.take(3).toList()

Here, we’re taking the first three elements of an infinite sequence and converting the resulting finite sequence to a list.

3. Conclusion

In this tutorial, we saw how to create different collections such as Lists, MutableLists, or even Arrays with repeating elements in them.

As usual, all the examples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.