As a quick note, if you ever need to fill/populate a Scala list with the same element X number of times, a simple solution is to use the
fill method, 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
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.
There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.