By Alvin Alexander. Last updated: January 26, 2020
As a quick note, if you ever need to fill/populate a Scala list with the same element X number of times, one solution is to use the fill
method that’s available to Scala sequences, like this:
scala> val x = List.fill(3)("foo")
x: List[String] = List(foo, foo, foo)
If you want to populate a list with different element values, another approach is to use the tabulate
method:
scala> val x = List.tabulate(5)(n => n * n)
x: List[Int] = List(0, 1, 4, 9, 16)
For more information, see my Five ways to create a Scala List tutorial.