I'm trying to read a csv file and return it as an array of arrays of doubles (Array[Array[Double]]). It's pretty clear how to read in a file line by line and immediately print it out, but not how to store it in a two-dimensional array. 
def readCSV() : Array[Array[Double]] = {
    val bufferedSource = io.Source.fromFile("/testData.csv")
    var matrix :Array[Array[Double]] = null
    for (line <- bufferedSource.getLines) {
        val cols = line.split(",").map(_.trim)
        matrix = matrix :+ cols
    }
    bufferedSource.close
    return matrix
}
Had some type issues and then realized I'm not doing what I thought I was doing. Any help pointing me on the right track would be very appreciated.
It seems your question was already answered. So just as a side note, you could write your code in a more scalaish way like this:
def readCSV() : Array[Array[Double]] = {
  io.Source.fromFile("/testData.csv")
    .getLines()
    .map(_.split(",").map(_.trim.toDouble))
    .toArray
}
                        1) You should start with an empty Array unstead of null. 
2) You append items to an Array with the operator :+
3) As your result type is Array[Array[Double]] you need to convert the strings of the csv to Double.
def readCSV() : Array[Array[Double]] = {
    val bufferedSource = io.Source.fromFile("/testData.csv")
    var matrix :Array[Array[Double]] = Array.empty
    for (line <- bufferedSource.getLines) {
        val cols = line.split(",").map(_.trim.toDouble)
        matrix = matrix :+ cols
    }
    bufferedSource.close
    return matrix
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With