2

I wrote this method

def compare[U, T <: Comparable[U]](a: T, b: U) = a.compareTo(b)

It works with String and Integer but not with Int or RichInt. So why isn't an Int automatically converted to an Integer?

SpiderPig
  • 21
  • 1

1 Answers1

4

Using a simple context bound would require the compiler to apply the implicit conversion before the converted value is passed to the method. I believe what you want is this, instead:

def compare[U, T <% Comparable[U]](a: T, b: U) = a.compareTo(b)

Here, the implicit wrapping of 'a' will happen inside the implementation of the method, so you should be able to get what you want. I'm not completely clear on what usage was failing you, though - you should try to include examples of what's not working so that we can be sure when we try to answer!

Kris Nuttycombe
  • 4,560
  • 1
  • 26
  • 29
  • 2
    This is definitely the right pattern to use. I suggest using Scala's Ordered instead of Comparable if you can. Ordered is a sub-trait of Comparable, so they're compatible. I do wonder about the performance implications of this though. For every comparison on ints, we know have a function call (and probably a box to Integer), which can't be good for heavy comparison operations like sorting. – Joshua Hartman Jun 10 '11 at 16:25
  • Thanks. So the only difference between <: and <% is how implicit conversions are being handled? – SpiderPig Jun 10 '11 at 16:36
  • 1
    <: is just a type bound whereas <% is a view bound. See this question for full details: http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala – mpilquist Jun 10 '11 at 16:55