Scala 中隐式函数转换和隐式 class 之间的区别
Difference between conversion with implicit function and implicit class in Scala
对于 Scala 中的隐式转换,我可以使用任一隐式转换函数
implicit def intToX(i:Int):X = new X(i)
1.myMethod // -1
或隐式class
implicit class X(i: Int) {
def myMethod = - i
}
1.myMethod // -1
两者有什么区别吗?什么时候我应该更喜欢一个?
有一个关于 implicit conversion vs. type class 的相关问题,但它只比较 隐式函数 和 type classes .我感兴趣的是与 implicit classes.
的区别
隐式class是隐式方法和class:[=14=的语法糖]
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 中添加了隐式 classes 因为定义 很常见新 class 定义 隐式方法 转换。
但是如果你不需要定义一个 new class 但定义到现有 class 的隐式转换你最好使用一个 隐式方法
好久没问你的问题了,从那以后事情似乎发生了变化。实际上,您现在应该始终选择隐式 类 而不是隐式转换。
隐式转换已被 Scala 标记为高级语言功能,编译器不鼓励使用它们(至少在 Scala 2.12
中是这样)。并且您需要在编译选项中添加一个额外的标志 (-language:implicitConversions
) 以将其关闭。 See scala-lang docs
此外,Scala 社区(或至少 LightBend/Typesafe 人)甚至计划总体上摆脱隐式转换。这是在 2017 年 11 月介绍 Scala 2.13 的会议演讲中提到的,您可以找到它 here。
对于 Scala 中的隐式转换,我可以使用任一隐式转换函数
implicit def intToX(i:Int):X = new X(i)
1.myMethod // -1
或隐式class
implicit class X(i: Int) {
def myMethod = - i
}
1.myMethod // -1
两者有什么区别吗?什么时候我应该更喜欢一个?
有一个关于 implicit conversion vs. type class 的相关问题,但它只比较 隐式函数 和 type classes .我感兴趣的是与 implicit classes.
的区别隐式class是隐式方法和class:[=14=的语法糖]
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 中添加了隐式 classes 因为定义 很常见新 class 定义 隐式方法 转换。
但是如果你不需要定义一个 new class 但定义到现有 class 的隐式转换你最好使用一个 隐式方法
好久没问你的问题了,从那以后事情似乎发生了变化。实际上,您现在应该始终选择隐式 类 而不是隐式转换。
隐式转换已被 Scala 标记为高级语言功能,编译器不鼓励使用它们(至少在 Scala 2.12
中是这样)。并且您需要在编译选项中添加一个额外的标志 (-language:implicitConversions
) 以将其关闭。 See scala-lang docs
此外,Scala 社区(或至少 LightBend/Typesafe 人)甚至计划总体上摆脱隐式转换。这是在 2017 年 11 月介绍 Scala 2.13 的会议演讲中提到的,您可以找到它 here。