Kratos Kratos - 1 year ago 123
Scala Question

Define a 2d list and append lists to it in a for loop, scala

I want to define a 2d list before a for loop and afterwards I want to append to it 1d lists in a for loop, like so:

var 2dEmptyList: listOf<List<String>>
for (element<-elements){
///do some stuff

The code above does not work. But I can't seem to find a solution for this and it is so simple!

Answer Source
scala> val elements = List("a", "b", "c")
elements: List[String] = List(a, b, c)

scala> val twoDimenstionalList: List[List[String]] = List.empty[List[String]]
twoDimenstionalList: List[List[String]] = List()

scala> val res = for(element <- elements) yield twoDimenstionalList ::: List(element)
res: List[List[]] = List(List(a), List(b), List(c))

Better still:

scala> twoDimenstionalList :::
res8: List[List[String]] = List(List(a), List(b), List(c))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download