Skip to Content
Course content

249: Value Classes for Type-Safe Primitives

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

Wait, why can't I just use a regular case class for this?

You absolutely could. If you wrap a Long in a standard case class UserId(value: Long), you get the type safety we're after. The problem is the heap. In a high-throughput system—say, processing a million user records in a stream—creating a million wrapper objects just to satisfy the compiler is a waste of memory and puts unnecessary pressure on the Garbage Collector.

That's where value classes come in. By extending AnyVal, you're telling the Scala compiler: "I want the type safety of a class during development, but at runtime, I want this to be treated as a primitive." Most of the time, the compiler will optimize the wrapper away entirely, leaving you with the raw performance of a Long or Int without the risk of accidentally swapping a UserId for an AccountId.

How do I actually implement these to stop "Primitive Obsession"?

The pattern is straightforward. You define a case class with exactly one public parameter and extend AnyVal. Let me show you a real-world scenario where this saves your skin. Imagine you're building a payment gateway where both User IDs and Account IDs are Long values.

case class UserId(value: Long) extends AnyVal
case class AccountId(value: Long) extends AnyVal

def transferFunds(from: AccountId, to: AccountId, amount: Double): Unit = {
  println(s"Transferring $$$amount from ${from.value} to ${to.value}")
}

val myUser = UserId(12345L)
val myAccount = AccountId(98765L)

// This would compile if we used raw Longs, but now it's a compile-time error:
// transferFunds(myUser, myAccount, 100.0) 

transferFunds(myAccount, AccountId(11111L), 100.0)

See what happened there? If those were just Longs, you could easily pass a UserId into the from parameter. Now, the compiler catches that mistake before the code ever runs. I've spent way too many hours debugging "swapped ID" bugs in my early career; this pattern effectively deletes that entire category of errors from your codebase.

Is there a catch? When does the "magic" optimization actually fail?

Yes, there is always a catch. The compiler tries its best, but it can't optimize everything. This is called "boxing." If you put your value class into a generic collection, like a List[UserId], Scala has to box the value into a real object because List expects a reference to an object, not a primitive long.

Similarly, if you use the value class in a way that requires it to be treated as a general Any or if you use it as a type parameter in a way that forces polymorphism, the compiler will allocate an object on the heap. It's not a deal-breaker—usually, the trade-off is still heavily in favor of value classes—but you shouldn't assume they are 100% "zero-cost" in every single edge case. Just be mindful when you're shoving them into complex generic structures.




📋 Practical Task

Refactoring the Order Management System for Type Safety

You have been handed a legacy piece of code for an Order Management System. Currently, the system uses String for everything, which is leading to bugs where OrderIds are being passed into functions expecting SkuIds (Stock Keeping Units).

Your task:

  • Create two value classes: OrderId and SkuId, both wrapping a String.
  • Refactor the shipItem function signature to use these new types instead of String.
  • Ensure the function body still accesses the underlying string value to print the log message.
// Current buggy code
def shipItem(orderId: String, skuId: String): Unit = {
  println(s"Shipping item $skuId for order $orderId")
}

val currentOrder = "ORD-123"
val currentSku = "SKU-99"

// This currently compiles, but is logically wrong!
shipItem(currentSku, currentOrder) 

Modify the code so that shipItem(currentSku, currentOrder) results in a compilation error, while shipItem(OrderId(currentOrder), SkuId(currentSku)) works perfectly.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.