Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects based on Double values?

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?

like image 246
DrGary Avatar asked Mar 01 '23 11:03

DrGary


1 Answers

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.

like image 114
Pavel Minaev Avatar answered Mar 07 '23 08:03

Pavel Minaev