2
votes

I noticed that while Java's instance capturing lambda expressions are translated into private instance methods, those for Scala are translated into public static method which takes the containing class as the first argument. Basically a desugared lambda expression seems to be in the following follow:

public static final boolean $anonfun$getLambda$1(com.test.SomeClass):
   ...

Is this always the case for Scala lambda expressions? If not, what will be the cases where they will be instance methods?

Also, why is the case for Scala lambda expressions which works differently from Java lambda expressions?

1
I believe since 2.12 they use the same underlying representation. In any case, do you have a particular reason for asking this? Or just curiosity? You shouldn't worry about those implementation details on normal day to day programming.Luis Miguel Mejía Suárez
@LuisMiguelMejíaSuárez I was actually asking about 2.12. For Scala 2.11 or below, anon functions compiled to inner anon classes. I was just curious and wanted to learn.Hoon

1 Answers

2
votes

Java can also create static methods; it depends on the context.

Scala's lambdas predate java's, this explains why the implementations are different:

Scala would probably attempt to copy what java does, except, when scala was written, java didn't have them yet.

Java has no interest in copying what scala does. In addition, the language design team for java is in direct communication with teams involved in the class file format and the JVM itself, thus, any concerns about performance are irrelevant - if the language implementation creates a scenario that the VM doesn't handle well, then that can be addressed 'in house' so to speak. This means java will design its language features in ways that other hosted-on-the-JVM languages just cannot do.

Pragmatically speaking, there is very little difference between a static method and a private instance method at the class level. A detail that basically just doesn't matter (the only real difference between static and instance methods at the class file level, once you posit that the static method takes as first arg a parameter that is a stand-in for the receiver, is dynamic dispatch - as a concept, that just isn't a thing private methods engage in, therefore, there is no real difference: They both take 'the receiver' as first argument).