Search code examples
scalatypestype-safety

Scala type-safety vs overhead (type vs class)


I have a graph, where each vertex has both an ID (which never changes) and a label (which changes frequently). Both are represented by longs.

Currently, I define the following types:

type VertexId = Long
type VertexLabel = Long

However, I discovered a bug today where I was passing in a VertexLabel to a function that expected a VertexId. This seems like the type of thing the scala compiler should be able to prevent.

I considered doing this instead:

case class VertexId(id: Long)
case class VertexLabel(label: Long)

But then there's extra overhead of "boxing" and "unboxing" and some extra memory usage.

Is there anyway to get the best of both worlds? Define both types as Longs in such a way that the compiler will prevent you from using one as the other?


Solution

  • Yes, you can use value classes:

    case class VertexId(val id: Long) extends AnyVal
    case class VertexLabel(val label: Long) extends AnyVal
    

    see http://docs.scala-lang.org/overviews/core/value-classes.html