Scala on the Command Line

The scala command can run in two modes, as an interactive shell or in batch mode. If we don’t provide any arguments, as we saw, the command brings up the interactive shell. However, if we provide a filename then it runs the code in it within a stand-alone JVM.

The file we provide may be a script file or an object file—that is, a compiler-generated .class file. By default, we can let the tool guess the type of the given files. Alternately, use the -howtorun option to tell it to treat the file as a script file or as an object file. Finally, to send Java properties, use the -Dproperty=value format. Let’s create a file and run it using the command.

Here’s a file named HelloWorld.scala with the following contents:

FirstStep/HelloWorld.scala
 
println(​"Hello World, Welcome to Scala"​)

Execute this script with the command scala HelloWorld.scala, as you see here along with the output:

 
>scala HelloWorld.scala
 
Hello World, Welcome to Scala

Follow the filename with any arguments you want to send to the program.

The ability to run code in a file as a script, without the extra steps of compilation, is quite convenient. Use this to write code related to system maintenance or administrative tasks, for example, and easily run them from your favorite IDEs, from the command line, or as part of a continuous integration chain of scripts.

Even though we don’t explicitly invoke the compiler when using the scala command, the code goes through rigorous compilation and type checking. The scala tool compiles the given script into bytecode in memory and then executes it.

Recall that in Java any stand-alone program is required to have a class with the static void main method. That rule applies to Scala programs also since they run on the JVM. However, Scala does not force us to implement the main method. Instead, it takes the trouble to roll the script into the traditional main method of a Main class. So, when we run the script, we’re running in an instance of the JVM main method of this synthesized Main class. You can view the bytecode generated during the execution of the scala command using the -savecompiled option before the filename, and the tool will save it to a JAR file.

Now that you know how to run Scala code stored in a file through the scala tool, let’s look at how to cut out that explicit usage of the command and directly run a stand-alone script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.38.117