Jack
Jack

Reputation: 5870

Can Scala Array add new element

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

Upvotes: 2

Views: 4963

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

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

Upvotes: 2

Related Questions