views:

98

answers:

1

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?

+8  A: 

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