0

When I read code, I found below function, this is an implicit function, but seems there is no input for this function. Always, the implicit function will be like this: implicit def int2Fraction(n: Int) = Fraction(n, 1) this function will transfer Int to Fraction. But for below code how it works? When the implicit conversion happens?

implicit def tupleOrderingDesc:Ordering[Tuple2[String,Int]] = {
      new Ordering[Tuple2[String, Int]] {
        override def compare(x: (String, Int), y: (String, Int)): Int = {
          if (y._1.compare(x._1) == 0) y._2.compare(x._2)
          else y._1.compare(x._1)
        }
      }
    }
Jason Zheng
  • 53
  • 1
  • 4

1 Answers1

2

Implicits (types, functions) are applied as soon as a function is called which has this type of implicit as implicit parameter. So the above will be applied when an Ordering of the specified type Tuple2[String,Int] is needed, e.g when comparing,sorting.

More detailed discussion can be found here: Easy idiomatic way to define Ordering for a simple case class

and on implicits in general, including Ordering: https://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html

awagen
  • 236
  • 2
  • 8