🔴 Scala Advanced

What is opaque type alias in Scala 3?

Answer

Opaque type aliases (Scala 3) create new types that are type-safe wrappers at compile time but have zero runtime overhead (unlike wrapper classes). Define: object Types { opaque type Email = String; object Email { def apply(s: String): Email = s } }. Outside the defining scope, Email is distinct from String — you cannot pass a raw String where an Email is expected. Inside the defining scope, Email is just String, so all String operations are available. This solves the "type alias loses type safety" problem without the boxing overhead of a wrapper class. Use cases: preventing mixing up IDs of different types (UserId vs ProductId), ensuring strings pass validation before use (Email, NonEmptyString). In Scala 2, this was approximated with value classes (extends AnyVal) but with limitations around equality and Null. Opaque types are the preferred Scala 3 approach for zero-cost type safety.