Ordering for java.sql.Date

353 views
Skip to first unread message

donny....@gmail.com

unread,
Aug 20, 2013, 2:01:12 PM8/20/13
to scala...@googlegroups.com
I have a List[java.sql.Date], and want to call list.max which requires an implicit Ordering[T]. In LowPriorityOrderingImplicits there is the method:
implicit def ordered[A <% Comparable[A]]: Ordering[A] = new Ordering[A] {
  def compare(x: A, y: A): Int = x compareTo y
}
That works for java.util.Date (which implements Comparable[java.util.Date]), but it doesn't work for java.sql.Date which extends java.util.Date but doesn't implement Comparable[java.sql.Date] because the inherited compareTo method from java.util.Date works fine.

Is there a method signature for the implicit conversion that will work for java.sql.Date and other classes like it?

Here are a few signatures I tried that I thought might work, but didn't:
implicit def ordered[A <: Comparable[A], B <: A] = new Ordering[B] {
  def compare(x: B, y: B) = ...
}
I was hoping for the compiler to infer A as java.util.Date and B as java.sql.Date.
I also tried [A <: Comparable[A], B >: A, C <: B with Comparable[C]] (satisfied by A=j.s.Date, B=j.u.Date, C=j.u.Date), and that doesn't work either.

(A thought I had: does the algorithm that checks if a type T can satisfy the constraints (eg for "A <: Comparable[A], B <: A") try the parent classes of T when we're dealing with List[+T]? Should it?)

Erik Osheim

unread,
Aug 20, 2013, 2:27:45 PM8/20/13
to donny....@gmail.com, scala...@googlegroups.com
On Tue, Aug 20, 2013 at 11:01:12AM -0700, donny....@gmail.com wrote:
> I have a List[java.sql.Date], and want to call list.max which requires an
> implicit Ordering[T]. In LowPriorityOrderingImplicits there is the method:
> implicit def ordered[A <% Comparable[A]]: Ordering[A] = new Ordering[A] {
> def compare(x: A, y: A): Int = x compareTo y
> }
> That works for java.util.Date (which implements
> Comparable[java.util.Date]), but it doesn't work for java.sql.Date which
> extends java.util.Date but doesn't implement Comparable[java.sql.Date]
> because the inherited compareTo method from java.util.Date works fine.

You'll want something like:

import java.sql.Date
implicit val sqlDateOrdering = new Ordering[Date] {
def compare(x: Date, y: Date): Int = x compareTo y
}

...assuming that (x compareTo y) is the code you want to run.

Hope this helps.

-- Erik
Reply all
Reply to author
Forward
0 new messages