0

In scala, I am trying to assign a 1D array to one row of a 2D array

var data: Array[Array[AnyRef]] = _
val line = "Year,Month,Day,City"
val temp = line.split(",").toArray.asInstanceOf[Array[AnyRef]]

When I tried

data(0)=temp

application will suspended without further warning or error msg. What is wrong with this approach? And how to do it properly? Thank you

2
  • data(0) = Array.ofDim[AnyRef](temp) Take a look at safaribooksonline.com/library/view/scala-cookbook/9781449340292/… Commented Aug 14, 2015 at 17:35
  • I am sorry, but this method doesn't compile. I tried data(0) = Array.ofDim[AnyRef](temp) as well, but it just suspended as before. Commented Aug 14, 2015 at 18:22

1 Answer 1

1

Your data array is not initialized. Try this.

object TwoDArray {

  var data: Array[Array[AnyRef]] = Array.ofDim[AnyRef](100,100)
  val line = "Year,Month,Day,City"
  val temp = line.split(",").toArray.asInstanceOf[Array[AnyRef]]

  def main(args: Array[String]) {
    data(0) = temp
    data.foreach(row => {
      val arrToStr = row.mkString(" ")
      if (!arrToStr.contains("null")) println(arrToStr)
    })
  }
}

Update: I initialized the array as 100x100, you can make it smaller as necessary. Also, the main method is only for testing. If you don't know the size of your 2D array, you may consider other data strictures that can grow dynamically, e.g. List of Lists

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

1 Comment

Nice point, once OP initialize the array, just calling data(0)=temp should work.

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.