Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

vector







Scala Vectors

  • Overview: Scala's Vector is an immutable collection that provides effective random access and updates. It's implemented as a trie (a tree-like data structure) with a branching factor of 32, balancing between quick access and functional updates.
  • Creating Vectors:
    val emptyVector: Vector[Int] = Vector()
    val vector: Vector[Int] = Vector(1, 2, 3, 4, 5)
    
  • Key Properties:
    • Immutable.
    • Efficient for large collections.
    • Provides fast random access and updates.







Basic Operations

  • Accessing Elements: Use the apply method or simply parentheses.
    val firstElement = vector(0)
    
  • Appending and Prepending Elements: Since Vectors are immutable, these operations return a new Vector.
    val appended = vector :+ 6
    val prepended = 0 +: vector
    
  • Concatenation: Combining two Vectors.
    val vector2 = Vector(6, 7, 8)
    val concatenated = vector ++ vector2
    







Transformations

  • Mapping: Apply a function to each element.
    val doubled = vector.map(_ * 2)
    
  • Filtering: Select elements based on a predicate.
    val evens = vector.filter(_ % 2 == 0)
    
  • Folding: Reduce elements using a binary operation.
    val sum = vector.foldLeft(0)(_ + _)
    







Advanced Features and Performance

  • Random Access Performance: Vectors offer excellent performance for both random reads and writes due to their trie-like structure, making them suitable for large collections.
  • Memory Footprint: While providing fast access, Vectors might have a larger memory footprint than simple sequences like Lists, due to their underlying structure.
  • Iteration Performance: Iterating over a Vector is efficient and comparable to iterating over an array.







Use Cases and Best Practices

  • When to Use Vectors:
    • Ideal for large collections requiring frequent reads and updates.
    • When you need a general-purpose, immutable collection with good performance characteristics.
  • Vector vs. List: Prefer Vectors over Lists for large collections or when you need fast access. Lists can be more efficient for operations that involve primarily head-based operations or when working with small collections.
  • Immutable Collections: Embrace the use of immutable collections like Vectors to leverage the benefits of functional programming, such as easier reasoning about code and inherent thread safety.







Converting Between Vectors and Other Collections

  • Conversion to Other Collections: Vectors can be easily converted to and from other collection types.
    val listFromVector = vector.toList
    val arrayFromVector = vector.toArray
    val seqFromVector = vector.toSeq