Command Line Scala
...Back to 5CS004
Using the Scala interpreter
You can use Scala in two ways, either as an interpreter, which reads each instruction you type in and executes it (like PHP, Python and Ruby), or you can compile Scala code to .class
files and run them on the Java Virtual Machine (like Java, Groovy, JRuby and so on). In general, it is useful to use the interpreter when you are "playing" with code and trying to find out what will work and what will not. It is more useful to compile code when you are writing code you want to use as a stand-alone program.
To start the Scala interpreter, use the scala
command, with no arguments:
$ scala Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_22). Type in expressions to have them evaluated. Type :help for more information. scala>
Like the BASH shell that comes with Ubuntu, Scala has a prompt that tells you it is ready for your next instruction. In this case the prompt is scala>
.
You can type any Scala command in, you do not have to create a new object
, although you can if you want to:
scala> println("Hello world!") Hello world! scala>
Compiling and running Scala code
- Edit your Scala code using
gedit
or whatever editor you prefer. Make sure that your filename ends in.scala
and the file name is the same as theobject
described in the file. For example:
$ cat >Main.scala object Main { def main(args: Array[String]): Unit = { println("Hello, world!") } } // Press Ctrl+D to close this stream to cat $
- Now you can compile your code using
scalac
(stands for Scala Compiler):
$ scalac Main.scala $
- The code has been compiled, and you should be able to see some JVM
.class
files that have been generated by the compiler:
$ ls Main* Main.class Main$.class Main.scala $
- To run the
Main
object, use thescala
command and pass it the name of the object you wish to run:
$ scala Main Hello, world! $
...Back to 5CS004