SpiderPig
SpiderPig

Reputation: 21

Scala - Generics + implicit conversion

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?

Upvotes: 2

Views: 656

Answers (1)

Kris Nuttycombe
Kris Nuttycombe

Reputation: 4580

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!

Upvotes: 4

Related Questions