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?

2
  • 1
    What confuses me a bit some times is when Arrays and other collections in Scala are said to be immutable so one would assume that updating array elements is not possible (like e.g. in Scala Saddle) but what it actually means is that once created as a the dimensions can not be changed but the contents yes ... Commented Feb 17, 2017 at 9:28
  • Many collections are immutable in Scala, but Arrays are just Java Arrays, and they are mutable. Commented Sep 27, 2017 at 1:58

1 Answer 1

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
    }
Sign up to request clarification or add additional context in comments.

3 Comments

yep, I thought that num represents size of an array, Thanks
@user1224307 It only represents the size if you use the new keyword. Array(1, 2, 3) is just an array with the elements 1, 2 and 3.
Worth pointing out that you can initialise the array with Array.tabulate so for example Array.tabulate(10)(identity) gives Array[Int](0, 1, 2, 3, 4, 5, 6, 7, 8, 9) and Array.tabulate(10)(_ * 2) gives Array[Int](0, 2, 4, 6, 8, 10, 12, 14, 16, 18)

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.