karteekkadari
karteekkadari

Reputation: 15

Unable to updating an array inside list's map function. Scala Programming

I am trying to update an Array[Array[String]] type when a map function is called on list.

var m : Array[Array[String]] = Array(Array(""))
var n : List((String, Double))
n contains 100 elements
i want to update m foreach element in n like
n.map(x => {
   m :+ Array("a","b","c");
   x
})

but I am ending up with empty array. Values are not appending to m. I want to try it for an RDD as well.

Upvotes: 1

Views: 331

Answers (1)

First, the idea of map is to transform the collection on which map is being called, not mutating other collection - foreach would be better.

Second, the reason why you end up with an empty array is because :+ creates a copy with the element added, it does not mutate the original array - scaladoc.

Third, arrays aren't the best collections for incremental building, because is not efficient to resize them, you can create a big array first and then updating every position by index (however, that would be very imperative), or you could use an ArrayBuffer scaladoc, or you could map the list and end up with a List[Array[A]] or a List[List[A]] (that would be the most functional way of doing it).

Fourth, what exactly you mean with trying it with and RDD as well... if you want to build an array by iterating a RDD, that's conceptually wrong. Or, if you want to build a RDD by iterating a List, that's conceptually wrong too.

Upvotes: 1

Related Questions