在此处解释的Scala 2中,我们有一个实现 trait的函数类型FunctionX
和一个非值类型的方法类型。我们可以将一个方法转换为方法值,它是函数类型的一个实例,如下所示:
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 中),但在 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 的函数和方法是相同还是非常相似的对象,或者至少差异已经显着减少?