val vs var vs lazy valImagine three types of shipping labels. This is Scala's variable system — one of the most common interview questions.
| Keyword | Mutable? | When Evaluated? | Metaphor |
|---|---|---|---|
val | ❌ Immutable | Immediately | 📦 Sealed package — once packed, can't reopen |
var | ✅ Mutable | Immediately | 📥 Open box — swap contents anytime |
lazy val | ❌ Immutable | On first access | 📨 Sealed package that's only built when someone asks for it |
Think of a case class like a pre-printed form. You define the fields once, and Scala fills in all the boring methods for you.
toString, equals, hashCode, copy method, apply (no "new" needed), unapply (pattern matching support)
"When would you use a case class?" → For immutable data containers. DTOs, API responses, config objects, events.
Imagine a phone and its charging dock. They share the same name, live together, and the dock provides utilities the phone can't do alone.
apply method is magic — lets you write Person("John", 25) without "new".static keyword (unlike Java). Companion objects are where you put "static-like" methods — factory methods, constants, utility functions that belong to the concept but not to any single instance.Two more topics interviewers sneak in. Let's nail them.
Every modification creates a new string. Like writing on a whiteboard, erasing, and writing on a fresh one each time. Fine for small changes.
Modifies in-place. Like having a notebook where you keep adding pages. Much faster for lots of text manipulation.