2

When I created a Scala Array and added one element, but the array length is still 0, and I can not got the added element although I can see it in the construction function.

scala> val arr = Array[String]()
arr: Array[String] = Array()

scala> arr:+"adf"
res9: Array[String] = Array(adf)

scala> println(arr(0))
java.lang.ArrayIndexOutOfBoundsException: 0
  ... 33 elided
1
  • You're creating a new array with :+ which is stored in res9 in your example since you didn't assign it to anywhere else. You can find the new element in that array. The original array is not altered in any way. Commented Nov 3, 2016 at 18:46

1 Answer 1

2

You declared Array of 0 size. It cannot have any elements. Your array is of size 0. Array[String]() is a array contructor syntax.

:+ creates a new Array with with the given element so the old array is empty even after doing the :+ operation.

You have to use ofDim function to declare the array first of certain size and then you can put elements inside using arr(index) = value syntax.

Once declared array size do not increase dynamically like list. Trying to append values would create new array instance.

or you can initialize the array during creation itself using the Array("apple", "ball") syntax.

val size = 1
val arr = Array.ofDim[String](size)
arr(0) = "apple"

Scala REPL

scala> val size = 1
size: Int = 1

scala> val arr = Array.ofDim[String](size)
arr: Array[String] = Array(null)

scala> arr(0) = "apple"

scala> arr(0)
res12: String = apple
Sign up to request clarification or add additional context in comments.

2 Comments

@tkachuko array size do not increase dynamically
@tkachuko trying to append would create new Array instances and Arrays are mutable

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.