Is method semantically equivalent to function in Scala 3?

Viewed 73

In Scala 2 as explained here we had a Function Type that was implementing trait FunctionX and Method Type that was a non-value type. We could transform a method to Method Value which was an instance of Function Type like this:

class Sample {
  def method(x:Int) = x+1
  val methodValue = method _
}

Now in Scala 3, we can leave the underscore so it looks more like this:

class Sample:
  def method(x:Int) = x+1
  val methodValue = method

Isn't the equality sign suggesting semantic equivalence of method and function value in val methodValue = method? Also in Scala 2 I couldn't use any methods (at least in Scastie with Scala version 2.13.5) on created method like apply but in Scala 3 I can do that suggesting that methods in Scala 3 are regular objects:

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

So is Scala 3 functions and methods the same or very similar objects or at least the difference has been significantly reduced?

1 Answers

Isn't the equality sign suggesting semantic equivalence of method and function value in val methodValue = method?

The key concept to understand is eta expansion which converts methods into functions. Scala 3 has automated this process so

The syntax m _ is no longer needed and will be deprecated in the future.

Hence methods and functions are not the same, however Scala 3 tries to transparently convert between them so programmers do not have to worry about the distinction.

Related