Search code examples
scalasortingpositiontraits

Sorting a ListBuffer by Position


Unfortunately, scala.util.parsing.input.Position does not extend Ordering[Position].

To sort a ListBuffer of errors based on their position, I use the following code:

semanticErrors.sortBy(_.pos)(new Ordering[Position] {
  def compare(x: Position, y: Position): Int = x.line - y.line 
}).toList

I'm sure this can be done more elegantly. But how? For example, I noticed that Position implements <. Is there a generic wrapper which turns something that supports < into an Ordering?


Interestingly, this seems to be a lot easier when converting to a List first:

semanticErrors.toList.sort((a, b) => a.pos < b.pos)

But this is probably not the most efficient solution. An in-place sort of the ListBuffer would be ideal.


Solution

  • Use sortWith as drexin says is easiest as a one-off, but a couple of notes:

    1) sort is deprecated, so don't use it. The docs tell you to use sortWith instead.

    2) Ordering is a typeclass, so things don't extend it (unlike Ordered) . You just need to have one in implicit scope, which would normally be in a companion object. However Position doesn't have a companion. So you can add the implicit yourself:

    implicit val posOrd: Ordering[Position] = Ordering.fromLessThan(_ < _)
    

    Then semanticErrors.sortBy(_.pos) should work.