Scala Language Getting started with Scala Language Hello World as a script


Example

Scala can be used as a scripting language. To demonstrate, create HelloWorld.scala with the following content:

println("Hello")

Execute it with the command-line interpreter (the $ is the command line prompt):

$ scala HelloWorld.scala
Hello

If you omit .scala (such as if you simply typed scala HelloWorld) the runner will look for a compiled .class file with bytecode instead of compiling and then executing the script.

Note: If scala is used as a scripting language no package can be defined.

In operating systems utilizing bash or similar shell terminals, Scala scripts can be executed using a 'shell preamble'. Create a file named HelloWorld.sh and place the following as its content:

#!/bin/sh
exec scala "$0" "$@"
!#
println("Hello")

The parts between #! and !# is the 'shell preamble', and is interpreted as a bash script. The rest is Scala.

Once you have saved the above file, you must grant it 'executable' permissions. In the shell you can do this:

$ chmod a+x HelloWorld.sh

(Note that this gives permission to everyone: read about chmod to learn how to set it for more specific sets of users.)

Now you can execute the script like this:

$ ./HelloWorld.sh