Scala中具有隐式函数的转换与隐式类之间的区别
对于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
或隐式类
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?
还有一个有关隐式转换与类型类的相关问题,但它仅比较了隐式函数 em>和类型类.我感兴趣的是与隐式类的区别.
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.
隐式类是隐式方法和一个类的语法糖:
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)
在 scala 2.10 中添加了
隐式类,因为用隐式方法定义新类是很常见的. strong>对其进行转换.
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