【问题标题】:Difference between conversion with implicit function and implicit class in ScalaScala中使用隐式函数和隐式类的转换之间的区别
【发布时间】:2015-08-29 13:34:03
【问题描述】:

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

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

1.myMethod // -1

或隐式类

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

1.myMethod // -1

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

有一个关于implicit conversion vs. type class 的相关问题,但它只比较隐式函数类型类。我感兴趣的是与隐式类的区别。

【问题讨论】:

标签: scala implicit-conversion


【解决方案1】:

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

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
  ...
}

将被编译器转换为:

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> 转换为它。

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

【讨论】:

    【解决方案2】:

    您问了一个问题已经有一段时间了,从那以后情况似乎发生了变化。实际上,您现在应该始终选择隐式类而不是隐式转换。

    隐式转换已被 scala 标记为高级语言功能,编译器不鼓励使用它们(至少在 Scala 2.12 中)。您需要在编译选项中添加一个额外的标志 (-language:implicitConversions) 以将其关闭。 See scala-lang docs

    此外,Scala 社区(或者至少是 LightBend/Typesafe 人员)甚至计划摆脱一般的隐式转换。这是在 2017 年 11 月的 Scala 2.13 会议演讲中提到的,你可以找到它here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多