scalavalue-class

Hierarchy of value classes in Scala?


I have defined the following class hierarchy where I want to restrict the the type parameter to be conformable with Double...

sealed abstract class Quantity[-T](value: T)(implicit ev: T <:< Double)

case class DiscreteQuantity(value: Long) extends Quantity[Long](value)

case class ContinuousQuantity(value: Double) extends Quantity[Double](value)

...is it possible to re-write the above hierarchy so that the concrete types are value classes? From the docs I know that value classes can not be extended, so that rules out having Quantity inherit from AnyVal. In order for concrete classes to inherit from AnyVal I need to make Quantity a trait, which is fine, but then I lose the contra-variant annotation on the type parameter.

Thoughts?


Solution

  • It is possible, but as I said in the comment: <:< and <: don't include weak conformance, so basically only Quantity[Double] can exist.

    sealed trait Quantity[-T <: Double] extends Any { 
      protected[this] def value: T 
    }
    
    case class ContinuousQuantity(value: Double) extends AnyVal with Quantity[Double]