我正嘗試使用帶有隱式排序的scala集合方法來豐富我的庫模式。如何將需要隱式排序的方法添加到scala集合對象
給出這樣的定義:
object ImplicitTest {
implicit def RichTraversableOnce[A](t: TraversableOnce[A]): RichTraversableOnce[A] =
new RichTraversableOnce[A](t)
class RichTraversableOnce[A](val t: TraversableOnce[A]) {
def myMinBy[B >: A](f: A => B)(implicit cmp: Ordering[B]): A = {
if (t.isEmpty)
throw new UnsupportedOperationException("empty.myMinBy")
t.reduceLeft((x, y) => if (cmp.lteq(f(x), f(y))) x else y)
}
}
}
如何走到這一步的測試:
@Test
def testOrdering {
import ImplicitTest._
val mx = List(1, 2, 7, 1, 4, 8, 2, 5, 47, 2, 7).myMinBy(_.toDouble)
// ...but this works:
// val mx = List(1, 2, 7, 1, 4, 8, 2, 5, 47, 2, 7).minBy(_.toDouble)
println(mx)
}
給我這個編譯錯誤?
error: No implicit Ordering defined for AnyVal{def getClass(): java.lang.Class[_ >: Int with Double <: AnyVal]}. val mx = List(1, 2, 7, 1, 4, 8, 2, 5, 47, 2, 7).myMinBy(_.toDouble)
我正在使用scala 2.9.1 – eirirlar