4

Sorting objects is simple enough by mixing in Ordered and providing a compare() function, as shown here. But what if your sorting value is a Double instead of an Int?

def compare(that: MyClass) = this.x - that.x

where x is a Double will lead to a compiler error: "type mismatch; found: Double required: Int"

Is there a way to use Doubles for the comparison instead of casting to Ints?

Community
  • 1
  • 1
DrGary
  • 3,321
  • 3
  • 20
  • 14

1 Answers1

8

The simplest way is to delegate to compare implementation of RichDouble (to which your Double will be implicitly converted):

def compare(that : MyClass) = x.compare(that.x)

The advantage of this approach is that it works the same way for all primitive types.

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289