0

I'm trying to append Array to List When writing data into a csv file as follows.

But, each Array was not appended to the List. How can I append each Array to a List.

Please help me with this.

import java.io.StringWriter
import au.com.bytecode.opencsv.CSVWriter
import scala.collection.JavaConversions._
import java.io.FileWriter
import java.io.BufferedWriter

var out = new BufferedWriter(new FileWriter("/Users/TestCom/Desktop/test_4.csv"));
var writer = new CSVWriter(out);
var outputSchema = Array("name","0h","20h")
var listOfRecords = List(outputSchema)

var numIters = 0
for(numIters <- 0 to 1){

    var testVal1 = numIters + 1
    var testVal2 = numIters + 2

    var eachArr = Array(testVal1, testVal2)
    listOfRecords ++ eachArr
}

writer.writeAll(listOfRecords)
out.close()

1 Answer 1

1

Change your line that does listOfRecords ++ eachArr to be listOfRecords = listOfRecords ++ eachArr.

The list is immutable so you must reassign after appending.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. Additionally, "listOfRecords = listOfRecords ++ eachArr" made a mismatch error. So, I changed the code to "listOfRecords = listOfRecords ++ List(eachArr)"
Glad to help. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.