【发布时间】:2012-01-04 15:56:04
【问题描述】:
我正在尝试使用带有隐式排序的 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)
}
给我这个编译错误?
错误:没有为 AnyVal{def getClass(): java.lang.Class[_ >: Int with Double <: anyval val mx="List(1,">
【问题讨论】:
标签: scala implicit-conversion implicit enrich-my-library