Opaque types

An opaque type is a new type with no cost: inside the object that declares it, it is the type it stands for; everywhere else it is a type of its own, and the compiler refuses to mix it with anything. It is how a program says that a Long is a user id without paying for a wrapper object, and how it keeps two ids of the same shape apart.

A type that is a Long inside its object

type UserId = Long with the opaque keyword is a Long to the code in object UserId and a new type everywhere else. The companion makes one with apply and reads it with an extension method:

opaque.scala

object UserId: opaque type UserId = Long def apply(value: Long): UserId = value extension (id: UserId) def value: Long = id @main def opaqueExample(): Unit = val id = UserId(42) println(id.value) println(UserId(7).value + 1) println(id)

scala-cli run --server=false opaque.scala

42
8
42

The third line prints 42, because at run time the value really is a Long and the JVM prints it. That is the cost of the type: none. The extension is the only way to get the number back outside the object, and the extension methods lesson takes that mechanism apart.

The error outside the companion

The same value in a program that does not go through the companion is a type error, which is exactly what the type is for:

leak.scala

object UserId: opaque type UserId = Long def apply(value: Long): UserId = value @main def leak(): Unit = val id = UserId(42) val raw: Long = id println(raw)

mkdir -p out
scalac -color:never -d out leak.scala 2>&1; echo "exit status: $?"

-- [E007] Type Mismatch Error: leak.scala:7:18 ---------------------------------
7 | val raw: Long = id
  | ^^
  | Found: (id : UserId.UserId)
  | Required: Long
  |
  | longer explanation available when compiling with `-explain`
1 error found
exit status: 1

Found: (id : UserId.UserId) is the compiler saying that the opaque type and Long are different types outside the companion. Inside it, the same expression compiles, which is what makes the type free: no boxing, no allocation, one check at the boundary.

Related

Article author: Arthur Isaev