Diego Martinoia Diego Martinoia - 1 month ago 6
Scala Question

Idiomatic approach to Scala Value Classes

Does anyone know if there is an idiomatic way to name the inner value of a Scala Value Class? Say I have a value class for a product id, is it better defined as:

case class ProductId(productId:String) extends AnyVal

case class ProductId(underlying:String) extends AnyVal

case class ProductId(value:String) extends AnyVal


Is it just a matter of preference or is there an idiomatic guideline?


The idiomatic approach is to make it a private val, now that you can.

The standard library, so far as standards go, prefers self.

implicit final class ArrowAssoc[A](private val self: A) extends AnyVal

There is also repr, recalling both the phrase "underlying runtime representation" from the scaladoc for AnyVal and the repr of collections.

class StringOps(override val repr: String) extends AnyVal with StringLike[String]

There's also a smattering of i and n.

Personally, I use the special identifier, YMMV.