← Back to Scala Course | Chapter 6: Collections Basics | Lesson 8 of 8

Vector and Range

In this page:

  1. Vector and Range

Vector and Range

Vector is an immutable, indexed sequence offering good performance for both random access and updates (returning a new Vector), unlike List which is fast at the front but slow for indexed access deep into the sequence. A Range, like 1 to 10, represents a sequence of evenly-spaced integers without actually storing every value in memory until needed. Ranges are frequently used to drive for loops or converted to a concrete collection with .toList/.toVector.

Note: Prefer Vector over List when your code does a lot of random (indexed) access rather than just processing elements front-to-back.

Example: Vector and Range

markup
object Main extends App {
  val nums = Vector(1, 2, 3, 4, 5)
  println(nums(2))
  println(nums.updated(2, 99))

  val range = 1 to 10 by 2
  println(range.toList)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.