Groovy comes with a compiler called groovyc
. For each script, groovyc
generates a class that extends groovy.lang.Script
, which contains a main method so that Java can execute it. The name of the compiled class matches the name of the script being compiled.
For example, with this HelloWorld.groovy
script:
println "Hello World"
That becomes something like this code:
class HelloWorld extends Script {
public static void main(String[] args) {
println "Hello World"
}
}
Scala comes with a compiler called scalac
.
For example, with the same HelloWorld.scala
script:
println("Hello World")
The code is not valid for scalac
, because the compiler expected class or object definition, but works in the Scala REPL Interpreter. How is possible? Is it wrapped in a class before the execution?
The code in a Scala-Script is first placed in a Scala object, then compiled to JVM-Bytecode and at last executed. You can see the generated Scala object by writing scala -Xprint:parser my_file.scala
:
package <empty> {
object Main extends scala.ScalaObject {
def <init>() = {
super.<init>();
()
};
def main(argv: Array[String]): scala.Unit = {
val args = argv;
{
final class $anon extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
println("hello world")
};
new $anon()
}
}
}
}