Reputation: 21
In the middle of learning Scala.
Having a hard time understanding creating an 2-d array then converting it to a 2-d list.
I would think creating an empty List[List]]
then iterating through the array while converting each array to a list and appending it to a the list.
This throws an error
var arr = Array(Array(0, 1), Array(2, 3))
var ans = List[List[Int]]()
for (e <- arr) {
ans += e.toList
}
Then I am given a type mismatch error:
found:
List[Int]
required:
Int
This error doesn't make sense to me.
Upvotes: 0
Views: 100
Reputation: 44928
Just
val ans = arr.map(_.toList).toList
If (for whatever reason) you wanted to make your loop run, you'd have to use :+=
, which would be desugared into ans = ans :+ e.toList
:
for (e <- arr) {
ans :+= e.toList
}
Note, however, that it would be way slower than the map
(like, wrong asymptotic behavior kind of slower, i.e. really bad), because appending to a list with :+
requires rebuilding the entire list in every iteration.
Upvotes: 2