-2

i have created a empty scala mutable list

import scala.collection.mutable.ListBuffer
val list_of_list : List[List[String]] = List.empty

i want to append elements to it as below

filtered_df.collect.map(
          r => {

            val val_list = List(r(0).toString,r(4).toString,r(5).toString)
            list_of_list += val_list
          }
        )

error that i am getting is

Error:(113, 26) value += is not a member of List[List[String]]
  Expression does not convert to assignment because receiver is not assignable.
            list_of_list += val_list

Can someone help

Sparker0i
  • 1,787
  • 4
  • 35
  • 60
  • 1
    You have to change that `val list_of_list` to `var list_of_list` and also change the type of `list_of_list` into a mutable alternative – Sparker0i May 16 '20 at 12:13

2 Answers2

1

Your declaration seems wrong:

val list_of_list : List[List[String]] = List.empty

means that you've declared scala.collection.immutable.List whose operations return a new list without changing the current.

To fix the error you need to change the outer List type to ListBuffer that you imported above the declaration as follows:

val list_of_list : ListBuffer[List[String]] = ListBuffer.empty

Also it looks like you don't to use map here unless you want to modify your data collected from DataFrame, so you can change it to foreach:

filtered_df.collect.foreach {
  r => {
    val val_list = List(r(0).toString,r(4).toString,r(5).toString)
    list_of_list += val_list
  }
}

Furthermore you can make it in a functional way without resorting to ListBuffer, by using immutable List and foldRight as follows:

val list_of_list: List[List[String]] = 
  filtered_df.collect.toList
    .foldRight(List.empty[List[String]])((r, acc) => List(r(0).toString,r(4).toString,r(5).toString) :: acc)

toList is used to achieve a stack safety when calling foldRight, because it's not stack safe for Arrays

More info about foldLeft and foldRight

Duelist
  • 1,562
  • 1
  • 9
  • 24
0

You have to change that val list_of_list to var list_of_list. That alone would not be enough as you also have to change the type of list_of_list into a mutable alternative.

Sparker0i
  • 1,787
  • 4
  • 35
  • 60