tags:

views:

245

answers:

3

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.

+1  A: 

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.

GClaramunt
+3  A: 

I just found this article

http://www.michaelnygard.com/blog/2009/05/units_of_measure_in_scala.html

Hope it helps.

I was going to post that too and then I realized the author of that article is most likely the original poster of this question :) Maybe he should answer his own question now...
Joe Holloway
Yes, that was me. I wrote this question first. Separately, while waiting for answers here, I received a tweet with links. I investigated the library, then wrote that blog post based on the library.I thought it would be odd (and might come off as self-promotion) to answer my own question with a link to my own blog!
mtnygard
+1  A: 

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.

Alex Baranosky