Question

I need support for quantities with units. I'd like the type system to enforce unit correctness as much as possible. For example, it shouldn't be possible to combine grams with dollars. I'm going down the path of parameterized types, but this code seems far more repetitious than Scala code I've seen from others.

abstract class UnitOfMeasure

abstract class Range[T] {
  type T <: UnitOfMeasure
}
class Quantity[T <: UnitOfMeasure](value: Double)
class DefiniteRange[T<:UnitOfMeasure](lowerBound: Quantity[T], upperBound: Quantity[T]) extends Range[T]
class Confidence(conf: Double) {
  require(0.0 <= conf && conf <= 1.0)
}
class ConfidenceInterval[T<:UnitOfMeasure](lowerBound: Quantity[T], upperBound: Quantity[T], confidence: Confidence) extends Range[T] {
    def this(lower: Quantity[T], upper: Quantity[T]) = this(lower, upper, new Confidence(.90))
}

Is there a cleaner way to do this? The drumbeat of "T<:UnitOfMeasure" is the main thing that's bothering me.

Was it helpful?

Solution

OTHER TIPS

I don't have the book, but maybe a self type is what you need. You can enclose your classes in another class and add your type definition to be used in the class scope.

From mdmcnlly:

I recall seeing an example in the Programming in Scala book that dealth with a base type of animals that had a compatible food, and subtypes that could only eat their compatible subtype and not food for others. I feel like it is related but I'm not sure. Maybe someone with the book handy can tease out the good nuggets. The gist of the solution is to use type members of a base class instead of these variance annotations all over the place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top