Open In App

How to create a List With the Same Repeated Element?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

There are many ways in Scala to create a list that has the same repeating entry. This is a brief explanation:

Using List.fill:

By using the List.fill function in Scala, you may generate a list with a certain number of members that are all initialized to the same value.

Scala
val repeatedList = List.fill(3)(42)
// This will create a list containing the integer 42 repeated 3 times: List(42, 42, 42)

Example:

Here’s an example demonstrating the creation of a list with the same repeated element:

Scala
val repeatedList = List.fill(3)(42)
println(repeatedList)

Output:

Screenshot-(369)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads