Why is scala.math.PartialOrdering.lteq abstract, rather than defined in terms of .tryCompare?

StackOverflow https://stackoverflow.com/questions/11176003

  •  16-06-2021
  •  | 
  •  

Question

It seems that scala.math.PartialOrdering.lteq must always be defined as (or at least, give the same result as):

override def lteq(x: Pattern, y: Pattern) = {
    tryCompare(x, y).map(_ <= 0).getOrElse(false)
}

Is there some reason this implementation isn't given in the scala.math.PartialOrdering trait?

Was it helpful?

Solution

My guess is to encourage writing a more efficient lteq, as all other methods fall back to lteq. So you wouldn't want to create an Option, then map it. I would rather ask the opposite -- why isn't tryCompare implemented by default, e.g.:

def tryCompare(x: T, y: T) = {
  val p1 = lteq(x, y)
  val p2 = lteq(y, x)
  if (p1) {
    if(p2) Some(0) else Some(-1)
  } else if (p2) Some(1) else None
}

...and you wouldn't need to write the ugly override modifier when implementing lteq.

As far as I can see tryCompare is never ever used within the whole Scala standard library body, so maybe it's just a 'left-over'...

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