DnP DnP - 1 month ago 8
Scala Question

Build a List of Arrays recursively in Scala

I am newbie to Scala and I am trying to build a list of arrays recursively in scala, here is the code I have, it is not throwing any error when I run it, but, its not printing anything when I try unCons.foreach(println)

val Tot = 5
val Num = 5

var unCons = ListBuffer[String]()

for(j <- 1 to Tot)
{
var OurArr = ListBuffer[String]()

for(i <- 1 to Num)
{
OurArr:+("true")
}

unCons:+(OurArr.toList)
}


The result I am expecting is something like this

[[true, true, true, true, true],
[true, true, true, true, true],
[true, true, true, true, true],
[true, true, true, true, true],
[true, true, true, true, true]]


Any idea, where I am going wrong?

Answer

The "Scala way" might be to use List.fill

scala> List.fill(5)(List.fill(5)(true))
res0: List[List[Boolean]] = List(List(true, true, true, true, true), List(true, true, true, true, true), List(true, true, true, true, true), List(true, true, true, true, true), List(true, true, true, true, true))