Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe primitives in Scala

Tags:

scala

I'd like to have type-safe "subclasses" of primitives in my Scala code without the performance penalty of boxing (for a very low-latency application). For example, something like this:

class Timestamp extends Long
class ProductId extends Long

def process(timestamp: Timestamp, productId: ProductId) {
  ...
}

val timestamp = 1: Timestamp // should not box
val productId = 1: ProductId // should not box

process(timestamp, productId) // should compile
process(productId, timestamp) // should NOT compile

There was a thread on the Scala User mailing list last year which seemed to conclude it wasn't possible without boxing, but I wonder if this is possible now in Scala 2.8.

like image 612
Mike Avatar asked Nov 21 '10 20:11

Mike


1 Answers

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!

like image 65
oxbow_lakes Avatar answered Nov 04 '22 05:11

oxbow_lakes