gpt4 book ai didi

scala - Scala中具有隐式函数的转换与隐式类之间的区别

转载 作者:行者123 更新时间:2023-12-04 09:14:10 26 4
gpt4 key购买 nike

对于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有一个相关的问题,但它仅比较隐式函数和类型类。我感兴趣的是与隐式类的区别。

最佳答案

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

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 中添加了 隐式类,因为通过定义 隐式方法转换来定义 新类是很常见的。

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

关于scala - Scala中具有隐式函数的转换与隐式类之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32286628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com