Vector Class, Part 2 (Scala 3 Video)
Vector
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 update and delete elements in a Vector
(while assigning the result to a new variable).
Updating Vector Elements
Updating a Vector
with its append and prepend methods:
val v1 = Vector(4,5,6) // Vector(4, 5, 6)
val v2 = v1 :+ 7 // Vector(4, 5, 6, 7)
val v3 = v2 ++ Seq(8,9) // Vector(4, 5, 6, 7, 8, 9)
val v4 = 3 +: v3 // Vector(3, 4, 5, 6, 7, 8, 9)
val v5 = Seq(1, 2) ++: v4 // Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)
If you prefer method names instead of symbolic names like these, you can use appended
, appendedAll
, prepended
, and prependedAll
.
Other update-related methods
val x = Vector(1,2,1,2)
x.distinct // Vector(1, 2)
x.map(_ * 2) // Vector(2, 4, 2, 4)
x.updated(0,100) // Vector(100, 2, 1, 2)
Deleting Vector Elements
A Vector
is an immutable sequence, so you don’t remove elements from a Vector
. Instead, you describe how to remove elements as you assign the results to a new collection.
Here are some examples of filtering methods, where filtering can be thought of as a form of deleting:
val a = Vector(10, 20, 30, 40, 10) // Vector(10, 20, 30, 40, 10)
a.distinct // Vector(10, 20, 30, 40)
a.drop(2) // Vector(30, 40, 10)
a.dropRight(2) // Vector(10, 20, 30)
a.dropWhile(_ < 25) // Vector(30, 40, 10)
a.filter(_ < 25) // Vector(10, 20, 10)
a.filter(_ > 100) // Vector()
a.find(_ > 20) // Some(30)
a.slice(2,4) // Vector(30, 40)
a.take(3) // Vector(10, 20, 30)
a.takeRight(2) // Vector(40, 10)
a.takeWhile(_ < 30) // Vector(10, 20)
Many more Vector examples
For more information, here’s a link to many more Scala Vector examples.
Update: All of my new videos are now on
LearnScala.dev