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

Vector and Range

A Vector is a fast, unchangeable list you can jump into at any position, and a Range is a counted sequence like one to ten. Both are handy for working through numbers and items.

In this page:

  1. Vector and Range
Syntax
scala
val vector = Vector(value1, value2, value3)
val range = 1 to 10
val stepped = 1 to 10 by 2

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting nums.updated(2, 99) to change nums, when a Vector is immutable and it returns a new vector.
  2. Writing 1 to 10 by 2 and expecting 10 in the result, when it gives 1, 3, 5, 7, 9.
  3. Assuming a Range stores every number, when it is computed lazily and stores only start, end and step.
Chapter Summary
  • List, Array, ArrayBuffer, Set, Map, and tuples store data in different ways.
  • List operations like head, tail, map, and filter transform collections.
  • Vector and Range provide additional sequence types.
🔒

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.