This page contains a collection of examples that show how to create and populate instances of the Scala Vector class.
Create a new Vector with initial elements
To create a new Scala Vector
with initial elements:
val nums = Vector(1, 2, 3)
val people = Vector(
Person("Emily"),
Person("Hannah"),
Person("Mercedes")
)
When you want to be clear/specific about what’s in the vector, use these approaches:
val x = Vector(1, 1.0, 1F) # Vector[Double] = Vector(1.0, 1.0, 1.0)
val x: Vector[Number] = Vector(1, 1.0, 1F) # Vector[Number] = Vector(1, 1.0, 1.0)
trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal
val animalHouse: Vector[Animal] = Vector( # Vector[Animal] = Vector(Dog(Rover), Cat(Felix))
Dog("Rover"),
Cat("Felix")
)
If you ever need to create an empty Scala vector:
val nums = Vector[Int]()
Remember the construction syntax is just syntactic sugar for apply
:
val nums = Vector(1, 2, 3) # Vector(1, 2, 3)
val nums = Vector.apply(1, 2, 3) # Vector(1, 2, 3)
Create a new Scala Vector by populating it
You can also create a new Vector
that’s populated with initial elements using a Range
:
# to, until
(1 to 5).toVector # Vector(1, 2, 3, 4, 5)
(1 until 5).toVector # Vector(1, 2, 3, 4)
(1 to 10 by 2).toVector # Vector(1, 3, 5, 7, 9)
(1 until 10 by 2).toVector # Vector(1, 3, 5, 7, 9)
(1 to 10).by(2).toVector # Vector(1, 3, 5, 7, 9)
('d' to 'h').toVector # Vector(d, e, f, g, h)
('d' until 'h').toVector # Vector(d, e, f, g)
('a' to 'f').by(2).toVector # Vector(a, c, e)
# range method
Vector.range(1, 3) # Vector(1, 2)
Vector.range(1, 6, 2) # Vector(1, 3, 5)
You can also use the fill
and tabulate
methods:
Vector.fill(3)("foo") # Vector(foo, foo, foo)
Vector.tabulate(3)(n => n * n) # Vector(0, 1, 4)
Vector.tabulate(4)(n => n * n) # Vector(0, 1, 4, 9)
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
More information
I created this tutorial to show how to create and populate a Scala Vector
, but for many more examples of how to work with Vector
, see my Scala Vector class syntax and method examples tutorial. These same techniques also work with other Scala sequential collections classes, including Seq
, List
, Array
, ArrayBuffer
, and more.