How to use the Scala tabulate method - Use on List, Array, Vector, Seq, and more

Here are a few examples of how to use the Scala tabulate method, which can be used to create and populate a List:

scala> val xs = List.tabulate(5)(_ + 1)
xs: List[Int] = List(1, 2, 3, 4, 5)

scala> val xs = List.tabulate(5)(_ + 2)
xs: List[Int] = List(2, 3, 4, 5, 6)

scala> val xs = List.tabulate(5)(_ * 2)
xs: List[Int] = List(0, 2, 4, 6, 8)

You can use the tabulate method on other Scala collections, including Array, Vector, Seq, and more:

scala> val xs = Array.tabulate(5)(_ * 2)
xs: Array[Int] = Array(0, 2, 4, 6, 8)

scala> val xs = Vector.tabulate(5)(_ * 2)
xs: scala.collection.immutable.Vector[Int] = Vector(0, 2, 4, 6, 8)

scala> val xs = Seq.tabulate(5)(_ * 2)
xs: Seq[Int] = List(0, 2, 4, 6, 8)

If you needed to see some examples of the Scala tabulate method, I hope these examples have been helpful.