11.7. Different Ways to Create and Update an Array
Problem
You want to create and optionally populate an Array
.
Solution
There are many different ways to define and populate an Array
. You can create an array with initial
values, in which case Scala can determine the array type
implicitly:
scala>val a = Array(1,2,3)
a: Array[Int] = Array(1, 2, 3) scala>val fruits = Array("Apple", "Banana", "Orange")
fruits: Array[String] = Array(Apple, Banana, Orange)
If you don’t like the type Scala determines, you can assign it manually:
// scala makes this Array[Double] scala>val x = Array(1, 2.0, 33D, 400L)
x: Array[Double] = Array(1.0, 2.0, 33.0, 400.0) // manually override the type scala>val x = Array[Number](1, 2.0, 33D, 400L)
x: Array[java.lang.Number] = Array(1, 2.0, 33.0, 400)
You can define an array with an initial size and type, and then populate it later:
// create an array with an initial size
val
fruits
=
new
Array
[
String
](
3
)
// somewhere later in the code ...
fruits
(
0
)
=
"Apple"
fruits
(
1
)
=
"Banana"
fruits
(
2
)
=
"Orange"
You can create a var
reference
to an array in a class, and then assign it later:
// this uses a null. don't do this in the real world
var
fruits
:
Array
[
String
]
=
_
// later ...
fruits
=
Array
(
"apple"
,
"banana"
)
The following examples show a handful of other ways to create and
populate an Array
:
scala>val x = Array.range(1, 10)
x: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) scala>val x = Array.range(0, 10, 2)
x: Array[Int] = Array(0, 2, 4, 6, 8) scala>val x = Array.fill(3)("foo") ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.