By Alvin Alexander. Last updated: August 28, 2024
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)
More Scala List class information
For more information, see: