Reputation: 13608
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.
Upvotes: 8
Views: 2337
Reputation: 6825
It's been a while sice you asked a question and it seems that things have changed since. Actually, you should always choose implicit classes over implicit conversions now.
Implicit conversions have been marked as an advanced language feature by scala and the compiler discourages use of them (at least in Scala 2.12
). And you need to add an extra flag (-language:implicitConversions
) to the compile options to turn it off. See scala-lang docs
Also, Scala community (or at least LightBend/Typesafe people) are even planning of getting rid of imlicit conversions in general. This was mention in a conference talk in 2017 Nov presenting Scala 2.13, you can find it here.
Upvotes: 4
Reputation: 917
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
Upvotes: 25