[scala] Array initializing in Scala

I'm new to Scala ,just started learning it today.I would like to know how to initialize an array in Scala.

Example Java code

String[] arr = { "Hello", "World" };

What is the equivalent of the above code in Scala ?

This question is related to scala array-initialization

The answer is


If you know Array's length but you don't know its content, you can use

val length = 5
val temp = Array.ofDim[String](length)

If you want to have two dimensions array but you don't know its content, you can use

val row = 5
val column = 3
val temp = Array.ofDim[String](row, column)

Of course, you can change String to other type.

If you already know its content, you can use

val temp = Array("a", "b")

Additional to Vasil's answer: If you have the values given as a Scala collection, you can write

val list = List(1,2,3,4,5)
val arr = Array[Int](list:_*)
println(arr.mkString)

But usually the toArray method is more handy:

val list = List(1,2,3,4,5)
val arr = list.toArray
println(arr.mkString)

To initialize an array filled with zeros, you can use:

> Array.fill[Byte](5)(0)
Array(0, 0, 0, 0, 0)

This is equivalent to Java's new byte[5].


Can also do more dynamic inits with fill, e.g.

Array.fill(10){scala.util.Random.nextInt(5)} 

==>

Array[Int] = Array(0, 1, 0, 0, 3, 2, 4, 1, 4, 3)

Another way of declaring multi-dimentional arrays:

Array.fill(4,3)("")

res3: Array[Array[String]] = Array(Array("", "", ""), Array("", "", ""),Array("", "", ""), Array("", "", ""))