Gary Sieling

Scala fill example

“Fill” is a static collection method, as one of several ways to instantiate a static list.

If you want a list of several values, you could do something like this:

val x = List(0, 0, 0, 0, 0)

But, fill makes this easier:

scala> List.fill(0)(5)
res22: List[Int] = List(0, 0, 0, 0, 0)

You can pass anything into this:

scala> List.fill(5)("test")
res21: List[String] = List(test, test, test, test, test)

You can even make multi-dimensional arrays this way:

scala> List.fill(2, 3)(0)
res26: List[List[Int]] = List(List(0, 0, 0), List(0, 0, 0))

scala> List.fill(2, 3, 4)(0)
res27: List[List[List[Int]]] = 
  List(
    List(
      List(0, 0, 0, 0), 
      List(0, 0, 0, 0), 
      List(0, 0, 0, 0)), 
    List(List(0, 0, 0, 0),
         List(0, 0, 0, 0), 
         List(0, 0, 0, 0)))
Exit mobile version