Search code examples
scalaimplicit-conversion

Difference between conversion with implicit function and implicit class in Scala


For implicit conversion in Scala, I can use either implicit conversion function

implicit def intToX(i:Int):X = new X(i)

1.myMethod // -1

or implicit class

implicit class X(i: Int) {
    def myMethod = - i
}

1.myMethod // -1

Is there any difference between the two? When should I prefer one over the other?

There is a related question about implicit conversion vs. type class but it only compares implicit functions and type classes. What I am interested is the difference from implicit classes.


Solution

  • Implicit class is a syntax sugar for implicit method and a class:

    http://docs.scala-lang.org/sips/completed/implicit-classes.html:

    For example, a definition of the form:

    implicit class RichInt(n: Int) extends Ordered[Int] {
      def min(m: Int): Int = if (n <= m) n else m
      ...
    }
    

    will be transformed by the compiler as follows:

    class RichInt(n: Int) extends Ordered[Int] {
      def min(m: Int): Int = if (n <= m) n else m
      ...
    }
    
    implicit final def RichInt(n: Int): RichInt = new RichInt(n)
    

    Implicit classes were added in scala 2.10 because it is was very common to define new class with defining implicit method conversion to it.

    But if you do not need to define a new class but defining implicit conversion to existing class you should better use an implicit method