0
def change(amount: Int, coins: Array[Int]): Int = {
        val dp = Array[Int](amount + 1)
        dp(0) = 1
        for {
            coin <- coins
            i <- coin to amount
        } dp(i) += dp(i - coin)
        dp(n)
}


when I'm executing above method, I'm getting following error.

java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at Main$.$anonfun$change$2(HelloWorld.scala:9)

But, when I Initialize the Array with new keyword(as following) and execute it, It is executing perfectly and I'm getting correct output.

Why?

def change(amount: Int, coins: Array[Int]): Int = {
        val dp = new Array[Int](amount + 1)
        dp(0) = 1
        for {
            coin <- coins
            i <- coin to amount
        } dp(i) += dp(i - coin)
        dp(n)
}

I don't know whether my understanding is correct or not, but only difference I found is mentioning new keyword. so my ask is, is there any connection to Array Initialization to get the ArrayIndexOutOfBoundExeption in the above methods, if yes, what is it?

I need Explanation in terms of Scala Programming.

3
  • Does this answer your question? "new" keyword in Scala Commented May 11, 2024 at 10:27
  • 1
    @GaëlJ that link has to be updated for Scala 3 - there you DON'T have to use new to call the constructor, unless there is apply method that would overshade it (see scastie.scala-lang.org/MateuszKubuszok/PQXkQFSaRneoyV9IOwJnRw/1). In that context the new keyword for Array would NOT be necessary if not for the apply(Int, Int*) overshadowing it. Commented May 11, 2024 at 17:15
  • 1
    Good catch @MateuszKubuszok :) Still not using Scala 3, I forgot they changed this! Commented May 11, 2024 at 17:21

2 Answers 2

2
new Array(integer)

calls the constructor with the number of elements. It wil create an array with an integer size, filled with zeroes.

Array(integer)

calls an apply method on Array companion object - basically a factory method that creates an array which is populated with values passed as varargs. So you would create an array of size 1, with an integer as its only value.

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

Comments

0

In order to create a new array with the specified length, the new keyword is required.

Calling the array constructor directly without 'new' creates a new array with the values provided. So in this case, it would create an array of length 1 with the value of amount + 1 in it.

Comments

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.