Skip to Content
Course content

23: List, Vector, and Array Operations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When should I actually use a List versus a Vector or an Array?

This is the most common question I get from people moving into Scala. On the surface, they all just "hold things," but their internal engines are completely different. If you pick the wrong one, your app will crawl once your data grows.

A List is a singly-linked list. It's fantastic if you're mostly adding elements to the front or processing things recursively. But if you try to access the 1,000th element of a List, Scala has to walk through the first 999 elements to get there. That's a performance killer.

A Vector is your "general purpose" workhorse. It's an immutable, indexed sequence. It provides nearly constant time for random access and appending to either end. If you aren't sure which one to use, just start with a Vector. I usually do.

Then there's the Array. This is a thin wrapper around a Java array. It's mutable and has a fixed size. I only use Arrays when I'm doing heavy numerical lifting or interfacing with a Java library that demands one. Since they're mutable, they can introduce bugs in multi-threaded code, so use them sparingly.

// A quick cheat sheet for your brain:
val myList = List("Apple", "Banana", "Cherry")    // Great for prepending, bad for random access
val myVec = Vector("Apple", "Banana", "Cherry")    // Great for everything, the safe default
val myArray = Array("Apple", "Banana", "Cherry")   // Fast, mutable, fixed size

I keep seeing :: and +:—what's the difference in how they work?

In Scala, how you add an element matters. For a List, the :: (cons) operator is the gold standard. It adds an element to the front of the list. Because it's a linked list, this is an $O(1)$ operation—it's practically instant regardless of how big the list is.

Now, if you use +: to add something to the end of a List, Scala has to copy the entire list to attach that new element. If you do this inside a loop, you've just turned your program into a snail.

Vectors are different. They are designed to handle additions to both ends efficiently. Here is how that looks in practice:

val history = List("Page 1", "Page 2")
val updatedHistory = "Page 3" :: history 
// Result: List("Page 3", "Page 2", "Page 1") - Fast!

val vecHistory = Vector("Page 1", "Page 2")
val updatedVec = vecHistory :+ "Page 3" 
// Result: Vector("Page 1", "Page 2", "Page 3") - Also fast!

How do I actually transform this data without writing messy for-loops?

Coming from Java or C#, the instinct is to create an empty collection and loop through the data to fill it. Please, don't do that in Scala. We use higher-order functions like map, filter, and flatMap. They work almost identically across Lists, Vectors, and Arrays.

Let's say you have a collection of raw user input strings that are messy. You want to trim them, remove the empty ones, and capitalize them. I'd chain these operations together like this:

val rawInputs = Vector("  alice  ", "  ", "bob  ", " charlie ")

val cleanedInputs = rawInputs
  .map(_.trim)                // Remove whitespace
  .filter(_.nonEmpty)         // Get rid of the empty strings
  .map(_.capitalize)          // Make them look pretty

// Result: Vector("Alice", "Bob", "Charlie")

I love this approach because it's declarative. You're telling Scala what you want, not how to move the pointers around. It's much harder to accidentally introduce an "off-by-one" error when you aren't managing indices manually.

What if I need to switch between these types?

You'll often find yourself in a situation where you've been using a Vector for the performance benefits, but a library function you're calling specifically requires a List or an Array. Luckily, Scala makes this trivial with conversion methods.

You just call .toList, .toVector, or .toArray. Just keep in mind that these methods create a new collection, so they aren't free. If you're doing this millions of times per second in a tight loop, it'll show up in your profiler.

val myVec = Vector(1, 2, 3)
val myList = myVec.toList    // Now it's a List
val myArray = myVec.toArray  // Now it's a Java-style Array



📋 Practical Task

Exercise: Order Processing Pipeline

You are building a small part of an e-commerce backend. You have a Vector of raw order amounts (as Double), but the data is noisy: it contains some negative numbers (errors) and some zero values that should be ignored.

Your Goal: Write a program that does the following:

  1. Starts with this input: val rawOrders = Vector(120.50, -5.0, 45.0, 0.0, 300.25, -10.0, 15.75)
  2. Filters out all values that are 0 or less.
  3. Applies a 10% tax to each remaining order using map.
  4. Converts the final result into an Array (because the legacy payment gateway API requires an Array[Double]).
  5. Prints the final Array to the console.

Expected Output: An array containing [132.55, 49.5, 330.275, 17.325] (approximately).

Rating
0 0

There are no comments for now.

to be the first to leave a comment.