424 APPENDIX C: Introduction to Scala
From the command line, enter the following to open the interactive interpreter, shown in Figure C-1.
scala
Using the interactive interpreter you can run your first “Hello world” program by using the println
method.
scala> println("Hello world");
Hello world
To quit the interpreter, type exit.
scala> exit
Executing Scala Code as a Script
Another way to execute Scala code is to type it into a text file and save it with the extension .scala.
You can then execute that code by typing filename.scala. For instance, you can create a file named
hello.scala with “Hello world” in it.
println("Hello world")
To execute it, you specify the file name as a parameter to the Scala command-line tool.
scala hello.scala
Compiling Scala Code
You can also execute Scala code by first compiling it using the scalac command-line tool. Then the
code will need to be executed in the context of an application, so you will need to add an object with
a main() method (see Listing C-1).
Listing C-1. The “Hello world” Program
- object HelloWorld {
- def main(args: Array[String]) {
- println("Hello, world")
- }
- }
Figure C-1. The Scala interactive interpreter