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?

1
  • 1
    This idiom is broken also for integer types, as it will produce wrong results on overflow. Commented Aug 4, 2009 at 19:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.