我有这段代码调用了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]
但这不起作用
答案 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]