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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Expecting
nums.updated(2, 99)to changenums, when aVectoris immutable and it returns a new vector. - Writing
1 to 10 by 2and expecting 10 in the result, when it gives 1, 3, 5, 7, 9. - Assuming a
Rangestores 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, andfiltertransform collections. VectorandRangeprovide additional sequence types.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: