Vector Class, Part 1


Vector is the preferred class to use when you want an immutable, indexed sequence class (meaning that you want rapid access to any element in the sequence, such as rapid access to the one-billionth element).

This first Vector video shows how to create a Vector and then read (access) its elements.

Creating a Vector

Creating a Vector:

val a = Vector(1, 2, 3)

case class Person(name: String)
val people = Vector(

val x = (1 to 100).toVector
val y = (0 to 100 by 5).toVector

Reading (or accessing) Vector elements

val names = Vector("bert", "ernie", "oscar")
names(0)    // "bert"
names(1)    // "ernie"
names(2)    // "oscar"

Using a Vector in a for loop:

for name <- names do println(name)

Using a Vector in a for expression:

val capNames = for name <- names yield name.capitalize

Many more Vector examples

For more information, here’s a link to many more Scala Vector examples.