Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initializing in Scala

People also ask

How do you create an array of objects in Scala?

Creating an Array and Accessing Its ElementsScala translates the first line in the example above into a call to Array::apply(), defined in the Array companion object. Such a method takes a variable number of values as input and creates an instance of Array[T], where T is the type of the elements.

What is array in Scala?

Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values.

How do you add to an array in Scala?

Use the concat() Method to Append Elements to an Array in Scala. Use the concat() function to combine two or more arrays. This approach creates a new array rather than altering the current ones. In the concat() method, we can pass more than one array as arguments.


scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

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)

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)