I have written a custom case class that checks that a Double
is in the interval [0,1] as:
implicit class DoubleIn01(val value: Double) extends Ordered[DoubleIn01] {
require(inBounds(0.0, value, 1.0), s"value $value should be in [0,1]")
override def toString: String = value.toString
override def hashCode(): Int = value.hashCode()
override def compare(that: DoubleIn01): Int = value.compare(that.value)
override def equals(obj: Any): Boolean =
obj match {
case o: Double => value.equals(o.asInstanceOf[Double])
case o: DoubleIn01 => value.equals(o.asInstanceOf[DoubleIn01].value)
case _ => false
}
def ==(that: Double): Boolean = value == that
}
And I have added an implicit function:
implicit def DoubleIn01ToDouble(x: DoubleIn01): Double = x.value
But that is not enough to ensure I can write:
assertEquals(DoubleIn01(0.5), 0.5)
(in testng, which checks the equality both ways).
What am I missing?
Note: I tried deriving from AnyVal
, but that didn’t allow me to have the require
statement in the class, apparently, so AnyVal
seems to be out.
This is a bit frustrating, as there doesn’t seem to be a simple way to write such a DoubleIn01
class in Scala. I spent several days on this, and each got bit one way or another by the limitations of AnyVal
, or implicit
. I really just want to not have to write more than the require
statement, and be interoperable with Java’s Double
and/or the native double
type, but apparently no such luck in Scala? (please prove me wrong