1

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?

davidrpugh
  • 4,363
  • 5
  • 32
  • 46
  • The code you start from doesn't work: "Cannot prove that Long <:< Double". `<:<` doesn't include weak conformance. – Jasper-M Dec 04 '16 at 11:32

1 Answers1

4

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]
Jasper-M
  • 14,966
  • 2
  • 26
  • 37