Scala中隐式函数转换与隐式类之间的区别

Mif*_*eet 7 scala implicit-conversion

对于Scala中的隐式转换,我可以使用隐式转换函数

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

1.myMethod // -1
Run Code Online (Sandbox Code Playgroud)

或隐含的类

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

1.myMethod // -1
Run Code Online (Sandbox Code Playgroud)

这两者有什么区别吗?我什么时候应该更喜欢一个?

关于隐式转换与类型类有一个相关的问题,但它只比较隐式函数类型类.我感兴趣的是与隐式类的区别.

Ник*_*кий 20

隐式类隐式方法和类的语法糖:

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

例如,表单的定义:

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

将由编译器转换如下:

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)
Run Code Online (Sandbox Code Playgroud)

scala 2.10中添加了隐式类,因为定义新类并定义隐式方法转换是非常常见的.

但是,如果您不需要定义新类但定义到现有类的隐式转换,则最好使用隐式方法