Tuesday, October 5, 2010

Scala Tutorial Part 0 - Four Ways To Run Your Scala Programs

So you have downloaded the scala distribution from scala-lang.org. $SCALA_HOME points to your scala installation and $SCALA_HOME/bin is in your PATH. Now you want to write your first scala program. This tutorial is going to show you four ways to run your first scala program. 


The interactive scala shell

The interactive scala shell can be started be typing the command  scala on the console. The scala shell allows you to enter scala code that is executed immediately.

The following listing shows how to run the classical "hello world" program:
$ scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> println("hello, scala world!");
hello, scala world!

scala> 

To quit the shell hit CTRL-D.


Running scripts

If you want to run the same code multiple times, you can put the code into a script. Simply put the above code into a file called HelloWorld.scala. To execute the script type
scala HelloWorld.scala
If you run scala programs interactively or as scripts you don't need classes. Especially you do not need a main class. This allows you to write scala scripts without lots of boilerplate code. But if you want to compile the code, you need to put your scala code into classes.

Running compiled code with the scala interpreter

To create a compilable version of our hello world application you need to create an object. Objects are the scala way to create static methods. We will explain more about objects in a future tutorial in this series.
Put the following code into a file called HelloWorldCompilable.scala:
object HelloWorld {
    def main (args: Array[String]) : Unit = {
        println("hello, scala world")
    }
}
If you are familiar with java you can understand this code. Unlike java scala allows you to give the file containing a class a different name than the class name.

To compile the code type
scalac HelloWorldCompilable.scala

The scala compiler creates two class files: HelloWorld.class and HelloWorld$.class. To run the compiled code type
scala HelloWorld
Make sure to omit the suffix .class. Typing scala HelloWorld.class will result in an error.


Running compiled code with the java interpreter

The scalac compiler creates java bytecode. Because of this you also can use the java interpreter to execute our HelloWorld class. All you have to do is to put the scala-library.jar into the classpath. This jar is located in the lib directory of your scala installation. To run the program type
java -classpath $SCALA_HOME/lib/scala-library.jar:. HelloWorld

This last example shows you one of the great strengths of scala. The fact that scalac generates java bytecode makes it possible to access every java library in scala code!

No comments:

Post a Comment