TExcelTAD
Home › Scala › Scala Opaque Types

Scala Opaque Types

Imagine a method transfer(from: String, to: String, amount: Double). Nothing stops a caller from swapping the two account IDs, or passing a price in cents where euros were expected. Wrapping each value in a case class helps, but costs an extra object per value. Scala 3's opaque type aliases give you distinct, type-safe types with zero runtime overhead.

Defining an opaque type

scala · try it yourself
object Ids:
  opaque type UserId = Long
  opaque type OrderId = Long

  object UserId:
    def apply(n: Long): UserId = n
  object OrderId:
    def apply(n: Long): OrderId = n

  extension (id: UserId) def userValue: Long = id
  extension (id: OrderId) def orderValue: Long = id

import Ids.*

def findOrder(user: UserId, order: OrderId): String =
  s"order ${order.orderValue} of user ${user.userValue}"

@main def run(): Unit =
  val u = UserId(7)
  val o = OrderId(1001)
  println(findOrder(u, o))
  // findOrder(o, u)   // compile error: Found OrderId, Required UserId
  // findOrder(7, 1001) // compile error: Found Int, Required UserId
order 1001 of user 7

Inside the object Ids, the compiler knows that UserId is a Long, so apply can simply return n. Outside, UserId is a completely separate type: you cannot mix it up with OrderId or with a plain Long. At run time it is just a long — no wrapper object exists.

Smart constructors

Because outsiders cannot create the type directly, the companion is the only gate. That is the perfect place for validation:

scala · try it yourself
object Domain:
  opaque type Email = String

  object Email:
    def from(raw: String): Either[String, Email] =
      val s = raw.trim.toLowerCase
      if s.matches("""[^@\s]+@[^@\s]+\.[a-z]+""") then Right(s)
      else Left(s"invalid email: '$raw'")

  extension (e: Email)
    def domain: String = e.substring(e.indexOf('@') + 1)
    def value: String = e

import Domain.*

@main def run(): Unit =
  val inputs = List("  Sam@Example.org ", "nope", "a@b.io")
  for in <- inputs do
    Email.from(in) match
      case Right(email) => println(s"ok: ${email.value} (domain ${email.domain})")
      case Left(err)    => println(err)
ok: sam@example.org (domain example.org)
invalid email: 'nope'
ok: a@b.io (domain b.io)

Every Email in the program has passed validation — the type is a proof.

Arithmetic on opaque types

You choose exactly which operations the new type supports by defining extension methods. Here money only supports adding money and multiplying by a quantity:

scala · try it yourself
object Money:
  opaque type Cents = Long

  def cents(n: Long): Cents = n
  def euros(e: Double): Cents = math.round(e * 100)

  extension (a: Cents)
    def +(b: Cents): Cents = a + b
    def *(qty: Int): Cents = a * qty
    def show: String = f"€${a / 100}.${a % 100}%02d"

import Money.*

@main def run(): Unit =
  val coffee = euros(2.80)
  val bagel = cents(195)
  val total = coffee * 2 + bagel
  println(total.show)
  // total * 1.5   // does not compile: no *(Double) defined
€7.55

Opaque type vs. alternatives

Approach Distinct type? Runtime cost Can restrict operations?
type UserId = Long (plain alias) no — fully interchangeable with Long none no
case class UserId(value: Long) yes one object per value yes
opaque type UserId = Long yes (outside its scope) none yes
scala · try it yourself
type Meters = Double            // transparent alias
opaque type Seconds = Double    // top-level opaque type

object Seconds:
  def apply(d: Double): Seconds = d

@main def run(): Unit =
  val distance: Meters = 100.0
  val plain: Double = distance  // fine: Meters IS Double
  println(plain)
  val t = Seconds(9.58)
  println(t)                    // prints the underlying Double
100.0
9.58

Note that println(t) shows 9.58: at run time the value really is a Double, so toString, equality and pattern matching see the underlying type.

Tip: Opaque types shine for identifiers, units of measure and validated strings — anything that is "just a number or string" in memory but must never be confused with another one in your code.

Test yourself

Outside its defining scope, can a UserId (opaque alias of Long) be passed where a Long is expected?

  1. Yes, always
  2. No, it is a distinct type
  3. Only with a cast
  4. Only in Scala 2

What is the runtime cost of an opaque type?

  1. One extra object per value
  2. None; values are represented by the underlying type
  3. A reflection call
  4. A boxing allocation on every use

Where is the best place to validate values of an opaque type?

  1. In every method that uses it
  2. In a smart constructor in its companion object
  3. In toString
  4. It cannot be validated