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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With