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.

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