Explain the significance and use of 'value classes' in Scala.

Instruction: Describe what value classes are, their benefits, and provide an example of how they are used.

Context: This question probes the candidate's understanding of value classes in Scala, including how they can be used to enhance type safety and performance with minimal runtime overhead.

Updated

A value class wraps one value in a distinct static type while allowing some uses to be represented without a separate wrapper object. A conventional declaration has one public val constructor parameter and extends AnyVal.

class UserId(val value: Int) extends AnyVal
class ProductId(val value: Int) extends AnyVal
def userLabel(id: UserId): String = s"user:${id.value}"

@main def valueClassExample(): Unit = {
  val user = new UserId(12)
  assert(userLabel(user) == "user:12")
  val boxed: Any = user
  assert(boxed.isInstanceOf[UserId])
  val ids = Array(user)
  assert(ids(0).value == 12)
}

Passing ProductId to userLabel fails to compile despite both wrapping an Int. The wrapper does not itself validate positivity, existence or ownership.

The allocation benefit is conditional. Treating a value class as another type, using it through generic code, storing it in an array or performing runtime type tests can require a wrapper. The example deliberately includes boxing contexts. A JIT may further optimize code, so this is not a measured allocation count or speedup. Value classes have restrictions on fields, inheritance and nesting. Value classes and allocation cases

Scala 3 retains value classes for compatibility. Opaque type aliases are the recommended alternative for many new wrapper-type APIs, but have their own visibility and representation rules. Choose the representation for the API's needs and verify performance with the actual compiler and workload. Opaque types

Related Questions