问题描述
在 Scala 2 as explained here 中,我们有一个 Function Type 实现了 trait FunctionX
和 Method Type,它是一个 非-值 类型。我们可以将方法转换为方法值,它是函数类型的一个实例,如下所示:
class Sample {
def method(x:Int) = x+1
val methodValue = method _
}
现在在 Scala 3 中,我们可以保留下划线,使其看起来更像这样:
class Sample:
def method(x:Int) = x+1
val methodValue = method
相等 符号是不是暗示了 val methodValue = method
中方法和函数值的语义等价?同样在 Scala 2 中,我无法在创建的方法上使用任何方法(至少在 Scala 2.13.5 版的 Scastie 中),例如 apply 但在 Scala 3 中我可以这样做,表明 Scala 3 中的方法是常规对象:
scala> val s = Sample()
val s: Sample = Sample@793c2cde
scala> s.method
val res13: Int => Int = Lambda$1530/856511870@ab595e8
scala> s.methodValue
val res14: Int => Int = Sample$$Lambda$1422/1191732945@1bbbede1
scala> s.method.
!= andThen compose finalize isinstanceOf notifyAll →
## apply ensuring formatted ne synchronized
-> asInstanceOf eq getClass nn toString
== clone equals hashCode notify wait
那么 Scala 3 的函数和方法是否是相同或非常相似的对象,或者至少差异已显着减少?
解决方法
等号是不是暗示方法和 val 中的函数值 methodValue = 方法?
要理解的关键概念是 eta 扩展,它将方法转换为函数。 Scala 3 有 automated 这个过程所以
语法 m _
不再需要,将在
未来。
因此方法和函数并不相同,但是 Scala 3 尝试在它们之间透明地转换,因此程序员不必担心区别。