Scala update array elements

I never thought I was asking such a simple question, but how to update an array element in scala

I declared an internal function inside my main object and I have something like this

object Main { def main(args: Array[String]) { def miniFunc(num: Int) { val myArray = Array[Double](num) for(i <- /* something*/) myArray(i) = //something } } } 

but I always get an exception. Can someone explain to me why and how I can solve this problem?

+8
arrays scala
source share
1 answer

Can you fill in the missing details? For example, what happens to the comments? What is the exception? (It's always best to ask a question with a complete sample code and make it clear what the problem is.)

Here is an example of building and updating an array:

 scala> val num: Int = 2 num: Int = 2 scala> val myArray = Array[Double](num) myArray: Array[Double] = Array(2.0) scala> myArray(0) = 4 scala> myArray res6: Array[Double] = Array(4.0) 

Perhaps you make the assumption that num represents the size of your array? In fact, this is just the (single) element in your array. Perhaps you wanted something like this:

  def miniFunc(num: Int) { val myArray = Array.fill(num)(0.0) for(i <- 0 until num) myArray(i) = i * 2 } 
+11
source share

All Articles