As you noted, Scala eventually compiles to JVM bytecode. An obvious instruction from the JVM instruction set, that has no equivalent in the Java language, is goto.
A Scala compiler might use goto for instance to optimize loops or tail-recursive methods. In this case, in Java you would have to emulate the behavior of a goto.
As Antimony hinted, a Turing complete language can at least emulate another Turing complete language. However the resulting program may be heavyweight and suboptimal.
As a final note, decompilers may help. I'm not familiar with the intrinsics of decompilers, but I assume that they rely a lot on patterns. I mean, for example, Java source pattern f(x) compiles to Bytecode pattern f'(x), so with a lot of hard work and experience, some manage to decompile Bytecode f'(y) to Java source f(y).
However, I've not heard of Scala decompilers yet (maybe someone's working on that).
[EDIT] About what I originally meant by emulating the behavior of a goto
:
I had in mind switch/case
statements inside a loop, and cdshines showed another way by using labeled break/continue
in a loop (though I believe that using "disregarded and condemned" features is not standard).
In either of these cases, in order to jump back to an earlier instruction, an idiomatic Java loop (for/while/do-while
) is required (any other suggestion?). An endless loop makes it easy to implement, a conditional loop would require more work, but I assume this is doable.
Also, goto
isn't limited to loops. In order to jump forward, Java would require other contructs.
A counterexample: in C, there are limitations but you don't have to go through such great lengths, because there's a goto
instruction.
As a related topic, if you're interested in non-idiomatic jumps in Scala, c.f. this old Q&A of mine. My point being, not only a Scala compiler might emit goto
in a way that's not natural in Java, but a developer can have a tight control on that with the help of Scala macros.
LabelDef
: A labelled expression. Not expressible in language syntax, but generated by the compiler to simulate while/do-while loops, and also by the pattern matcher. In my past tests, it could be used for forward jumps as well. In Scala Internals, developers wrote about to removing LabelDef
, but I don't know if and when they would.
Therefore, yes you can reproduce the behavior of goto
in Java, but because of the complexity involved in so doing, that is not what I would call standard Java, IMHO. Maybe my wording is incorrect, but in my mind the reproduction of an elementary behavior by complex means is an "emulation" of that behavior.
Cheers.