Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala updating Array elements

Tags:

arrays

scala

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?

like image 625
user1224307 Avatar asked Feb 21 '12 20:02

user1224307


People also ask

Are arrays mutable in Scala?

Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size can't change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala. collection.

Can you append to an array in Scala?

Again, the only trick here is knowing that you can't add elements to a Scala Array , and therefore, if you want to create an array that can be resized, you need to use the ArrayBuffer class instead.

How do I add elements to a Scala list?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.

What is the difference between list and array in Scala?

Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents a linked list whereas arrays are flat.


1 Answers

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
    }
like image 139
dhg Avatar answered Oct 05 '22 03:10

dhg