如何修改此订购?

时间:2019-05-14 16:51:17

标签: scala traits

我有这段代码调用了Longs的默认比较器:

val ordering = implicitly[Ordering[Long]]

如何创建自己的订单并使用implicitly调用?

我尝试过:

trait MyOrdering extends Ordering[Long] {
  override def compare(x: Long, y: Long): Int = x compare y
}

val ordering = implicitly[MyOrdering]

但这不起作用

1 个答案:

答案 0 :(得分:2)

您需要将新的Ordering实现的实例放入隐式命名空间。

implicit val mo :MyOrdering = new MyOrdering {}

val ordering = implicitly[MyOrdering]

您也可以将trait更改为implicit object,但还需要修改implicitly参数。

implicit object MyOrdering extends Ordering[Long] {
  override def compare(x: Long, y: Long): Int = x compare y
}

val ordering = implicitly[MyOrdering.type]