Alex Rivera | Logout

Scala updating Array elements

Asked 2012-02-21T20:40:45.367
19

I never thought I would be asking such a simple question but how do I update array element in scala

I have declared inner 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, Could someone explain me why and how can I solve this problem?

Edit
Report

1 Answer

20

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

Here's an example of Array construction and updating:

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 are making the assumption that num represents the size of your array? In fact, it is simply the (only) element in your array. Maybe 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
    }
answered 2012-02-21T20:51:53.340

Your Answer