Scala中具有隐式函数的转换与隐式类之间的区别 [英] Difference between conversion with implicit function and implicit class in Scala

查看:253
本文介绍了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

这篇关于Scala中具有隐式函数的转换与隐式类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆