Type-safe primitives in Scala

Why not use type aliases instead? I appreciate that they are not perfect (i.e. they do not solve your compilation issue), but they can make your code clearer without taking the performance hit?

type Timestamp = Long
type ProductId = Long

Then you can write methods which use the pimp my library pattern and let the JVM use escape analysis to remove the runtime overhead:

class RichTimestamp(self: Timestamp) {
  //whatever you want here
}

Note that all the usual caveats apply: unless you are extremely sure (because you are doing ultra-low-latency programming e.g.), the performance hit of using the boxed type is probably not a concern. I deal with systems processing tens of millions of inputs a day with no issues whatsoever!


The root of the Scala type hierarchy is Any with children AnyVal and Anyref. All of the integral types (like Long in your example) descend from AnyVal and you can't create subclasses in that side of the tree. Children of AnyVal represent low level types within the JVM. Type-erasure means that at runtime there really is no AnyVal anymore and if you could make Timestamp it would also be lost at runtime. You need boxing/unboxing as a place to store your wrapper type information.

case class Timestamp(ts: Long)

A good JVM can eliminate a lot of the boxing/unboxing overhead at runtime. For example, see Experiences with escape analysis enabled on the JVM

Tags:

Scala