Opaque Types
Zero-cost abstractions.
What Are Opaque Types?
Opaque types are a Scala 3 feature for creating zero-cost abstractions. They give a distinct type at compile time but compile down to the underlying type with no runtime wrapping.
- Type safety of a wrapper class.
- Zero allocation overhead.
object Distances:
opaque type Meters = Double
object Main:
def main(args: Array[String]): Unit =
println("Opaque types compile to their underlying type")Declaring an Opaque Type
Declare an opaque type inside an object or class. Outside that scope, Meters and Double are treated as different types.
object Distances:
opaque type Meters = Double
def meters(d: Double): Meters = d
def toDouble(m: Meters): Double = m
object Main:
def main(args: Array[String]): Unit =
val d = Distances.meters(5.0)
println(Distances.toDouble(d))