Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Order->Ordering implicit conversion to implicits, instances #1670

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion core/src/main/scala/cats/instances/order.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package instances

import cats.functor.Contravariant

trait OrderInstances {
trait OrderInstances extends cats.kernel.OrderToOrderingConversion {

implicit val catsFunctorContravariantForOrder: Contravariant[Order] =
new Contravariant[Order] {
Expand All @@ -14,3 +14,4 @@ trait OrderInstances {
def contramap[A, B](fa: Order[A])(f: B => A): Order[B] = fa.on(f)
}
}

9 changes: 9 additions & 0 deletions kernel/src/main/scala/cats/kernel/Order.scala
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,15 @@ abstract class OrderFunctions[O[T] <: Order[T]] extends PartialOrderFunctions[O]
ev.max(x, y)
}

trait OrderToOrderingConversion {
/**
* Implicitly derive a `scala.math.Ordering[A]` from a `Order[A]`
* instance.
*/
implicit def catsKernelOrderingForOrder[A](implicit ev: Order[A]): Ordering[A] =
ev.toOrdering
}

object Order extends OrderFunctions[Order] {
/**
* Access an implicit `Order[A]`.
Expand Down
14 changes: 14 additions & 0 deletions tests/src/test/scala/cats/tests/OrderTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,18 @@ class OrderTests extends FunSuite {
Invariant[Order]
Contravariant[Order]
}

// ambiguity test:
// the Ordering instance from the Order instance should be trumped
// by the one provided in the Ordering companion object
{
import cats.instances.all._
Ordering[String]
class C
implicit val ording: Ordering[C] = new Ordering[C] {
def compare(x: C, y: C) = 0
}
implicit val ord: Order[C] = Order.allEqual
Ordering[C]
}
}