2
votes

I'm trying to utilize the enrich-my-library pattern with scala collections methods with implicit ordering.

Given this definition:

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)
    }
  }
}

How come this test:

 @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)
  }

Gives me this compilation error?

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)

1

1 Answers

4
votes

There is no reason for your B >: A in myMinBy. This is where AnyVal comes from, least upper bound for Int and Double. Your code works with myMinBy[B](...)