Authors Top

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this tutorial, we’ll see how we can create a List with the same repeated element in Scala.

2. Creating a List With the Same Repeated Element

A List with the same repeating element can be created in a variety of ways.  We’ll explore these now by creating a List containing the word “element” five times.

2.1. Using a Loop Approach

Let’s start by using a naïve approach and using a loop to achieve our goal:

scala> (for(i <- 1 to 5) yield "element").toList
val res0: List[String] = List(element, element, element, element, element)

We can also use the map() method in a very similar way:

scala> (0 until 5).map(_ => "element").toList
val res1: List[String] = List(element, element, element, element, element)

While these naïve solutions work, there’s a more idiomatic approach we’ll see next.

2.2. Using List‘s fill() method

Since List is a subclass of Seq, we can use its fill() method to get a List with the same repeated element:

scala> List.fill(5)("element")
val res2: List[String] = List(element, element, element, element, element)

This solution is more idiomatic and straightforward.

3. Conclusion

In this article, we learned how to create a List with the same repeated element in Scala.

Authors Bottom

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

guest
0 Comments
Inline Feedbacks
View all comments