Think of collections as different types of storage containers. A freezer (immutable β locked), a fridge (mutable β swap items in/out), each with its own purpose.
| Collection | Type | Ordered? | Duplicates? | Use Case |
|---|---|---|---|---|
List | Immutable | β | β | Default go-to sequence |
Vector | Immutable | β | β | Fast random access |
Set | Immutable | β | β | Unique elements only |
Map | Immutable | β | Keys unique | Key-value lookups |
ArrayBuffer | Mutable | β | β | When you need to grow/shrink |
HashMap | Mutable | β | Keys unique | Frequently changing map |
List(...) or Map(...), you get the immutable version by default. This is a deliberate design choice for thread safety and functional purity. You have to explicitly import mutable collections.These are the most tested operations in Scala interviews. Think of them as three different conveyor belt machines in a factory.
Transform each element 1-to-1. Input: N items β Output: N items. Like stamping every letter in a pile.
Transform + flatten. Each element can produce multiple results, then they're merged into one flat list.
Side-effects only. Print, log, save β but returns Unit (nothing). Don't use for transformations!
Think of these as a workshop toolkit. Each tool solves a specific type of data problem.
reduce crashes on empty collections (no starting value). foldLeft takes an initial value, so it's safe on empty collections. Always prefer foldLeft in production.Think of immutable as stone tablets (carved once, read forever) and mutable as a whiteboard (erase and rewrite anytime).
| Aspect | Immutable (default) | Mutable |
|---|---|---|
| Thread safety | β Safe to share | β οΈ Need synchronization |
| Performance | Slight overhead on updates | Faster updates in-place |
| Debugging | Easier (data never changes) | Harder (who changed it?) |
| FP style | β Preferred | β Avoid if possible |
| Import needed? | No (default) | Yes: import scala.collection.mutable |
List("a b", "c d").flatMap(_.split(" ")) return?List().reduce(_ + _) on an empty list. What happens?