In Scala, I would like to write generic classes that use type operators>, /, *, etc., but I don't see how to restrict T to make this work.
I looked at the T constraint using Ordered [T], but that doesn't seem to work, since only RichXXX (like RichInt) extends it, not Int, etc. I also saw Numeric [T], is it only available in Scala 2.8?
Here is an example:
class MaxOfList[T](list: List[T] ) { def max = { val seed: Option[T] = None list .map( t => Some(t)) // Get the max .foldLeft(seed)((i,m) => getMax(i,m) ) } private def getMax(x: Option[T], y: Option[T]) = { if ( x.isDefined && y.isDefined ) if ( x > y ) x else y else if ( x.isDefined ) x else y } }
This class will not compile, because there are many Ts that do not support> etc.
Thoughts?
Now I used the MixIn tag to get around this:
trait MaxFunction[T] { def getMax(x:T, y:T): T } trait IntMaxFunction extends MaxFunction[Int] { def getMax(x: Int, y: Int) = x.max(y) } trait DoubleMaxFunction extends MaxFunction[Double] { def getMax(x: Double, y: Double) = x.max(y) }
What if we change the original class, we can mix it during instance creation.
PS Mitch, inspired by your rewriting of getMax, is another one:
private def getMax(xOption: Option[T], yOption: Option[T]): Option[T] = (xOption,yOption) match { case (Some(x),Some(y)) => if ( x > y ) xOption else yOption case (Some(x), _) => xOption case _ => yOption }