Daniel Wu
Daniel Wu

Reputation: 6003

compile error when use ordered type

The rowset has a column of item_key whose type in Int. and I want to know whether that column is bigger than a specific value or not.

def bigger[T: Ordered](a: ResultSet, columnName: String, compare: T): Boolean =
    (a.getObject(columnName).asInstanceOf[Ordered[T]] > compare)


bigger[Int](rs, "item_key", 5034533);   

But it throws the following compile error when calling bigger[Int](rs, "item_key", 5034533); where is the problem is?

Multiple markers at this line
    - could not find implicit value for evidence parameter of type Ordered[Int]
    - not enough arguments for method bigger: (implicit evidence$9: Ordered[Int])Boolean. Unspecified value parameter 
     evidence$9.
    - could not find implicit value for evidence parameter of type Ordered[Int]
    - not enough arguments for method bigger: (implicit evidence$1: Ordered[Int])Boolean. Unspecified value parameter 
     evidence$1.

Upvotes: 1

Views: 374

Answers (1)

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14318

Ordered[T] trait represents a single, natural ordering for a type should be used as a mixin into a class, where you have to provide implementation for compare(other : T). You're trying to use it as a typeclass. If you want an implicit ordering, which also means there can be multiple available orderings, you should use Ordering[T] instead.

def bigger[T](a: ResultSet, columnName: String, compare: T)(implicit ord : Ordering[T]) =
    ord.gt(a.getObject(columnName).asInstanceOf[T], compare)

Now, if you want to use Ordered, that means all your types will have to mix in Ordered[T]:

def bigger[T <: Ordered[T]](a: ResultSet, columnName: String, compare: T) =
    a.getObject(columnName).asInstanceOf[T] > compare

which is probably not what you want. You won't be able to use it with, for example, Int, since it does not extend Ordered[Int].

Other option would be to provide view bound:

def bigger[T <% Ordered[T]](a: ResultSet, columnName: String, compare: T) =
    a.getObject(columnName).asInstanceOf[T] > compare

which works fine (because there's a conversion from Int to Ordered[Int]), although I think that generally typeclass approach is now favored instead of view bounds - it's a bit subjective and if I'm wrong, please someone correct me.

Upvotes: 4

Related Questions