Hello World with Scala

Advertisement

Advertisement

Scala is a an object oriented functional language built on top of the Java Virtual Machine. (JVM). Because it is an extension of Java, you still have everything available to you as you normally would in Java. Check out this Hello World example.

Source Code

We are going to create a file named HelloWorld.scala. In the Java convention, the file name will match the class name and we will have one class per file. We first create the top level object named HelloWorld and we implement a main() function. When the program is run, main() will be the first thing executed.

// HelloWorld.scala
object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world!")
  }
}

Compiling

Compile a source file to a .class file with scalac

scalac HelloWorld.scala

Running

After compiling and getting the .class file, invoke the scala executable and pass it the class name you want to run. The class should contain a main method.

scala HelloWorld

Running Interactively

Scala has an interactive shell where you can run code. Run scala to get in to the shell. Try running commands like println().

println("Testing!")

Scripting

Scala programs can be scripted but the shebang is a little more complicated than a typical #!/bin/bash. Look at the sample below.

#!/bin/sh
exec scala "$0" "$@"
!#

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello, world! " + args.toList)
  }
}
HelloWorld.main(args)

Advertisement

Advertisement