【问题标题】:How to add methods that takes implicit ordering to a scala collection object如何将采用隐式排序的方法添加到 scala 集合对象
【发布时间】: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


    【解决方案1】:

    myMinBy 中的B &gt;: A 没有任何理由。这就是AnyVal 的来源,IntDouble 的最小上限。您的代码适用于myMinBy[B](...)

    【讨论】:

    • 感谢 didierd,只是我需要的一点提示!
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2013-04-29
    • 2013-10-20
    相关资源
    最近更新 更多