Invokedynamic and Implicit Methods

As I understand it, after reading this message about the new invokedynamic bytecode command in JDK 7, it allows you to call methods on objects that are not statically defined in the object class, and these method calls are resolved for some specific static methods in some other class, intercepting the target permission to call the method (the message gives an example).

Does this mean that Java 7 classes can have implicit methods like Scala? If not, how does the implicit method resolution in Scala differ from the resolution of the invokedynamic method?

+4
source share
2 answers

This is completely unrelated. Implicits in scala are fully resolved at compile time . The compiler inserts what you could write yourself. If he cannot do this, an error occurs during compilation. InvokeDynamic is a search for a method at runtime and a failure at runtime if it cannot be found.

In particular, if you write in scala xm() , where there is no method m in type x, it will look for an implicit conversion, that is, a function, say f, that is in scope (you could call f for now), which marked as implicit , which will take x as a parameter, and the result of which has a method m (the rules have much more details, but this is the essence). If he finds such a method, he will replace xm() with the correctly printed f(x).m() . It could also be written in code, and it would have to be in java. If such a function f is not found, then a compile-time error occurs.

This happens the exact same way if you call g(x) and x not for the correct type to be passed to g . If there exists a function f such that f(x) is of the correct type, then it will replace the code with g(f(x)) . Again, you could write this in a simple scala, and again, if there is no such method, it will not compile.

Dynamic does not have to worry too much at compile time if the method m exists in x and looks for it at runtime. This is how a dynamic language works, such as JRuby or Groovy. There is something about scala that is characteristic of Dynamic (labeled experimentally).

+13
source

The called dynamic bytecode will help speed up dynamic languages ​​in the JVM. It will also speed up access to structural types in Scala. An alternative to invokedynamic (and only an option before JDK 7) is reflection, which is really slow.

The Java language is statically typed and has no functions that use invokedynamic (except for explicit reflexive method calls using java.lang.invoke.MethodHandle , according to this question ).

Scala implicits are actually statically resolved and therefore not related to invokedynamic. For more details on how this works, see Daniel Sobral: " Where does Scala look for absenteeism?

+5
source

All Articles