Tuesday, 24 June 2014

The "Hello, World" Program In Scala

    While learning any programming language, we were used to execute a program that prints "Hello, World" as the first program . Here is the standard Hello World program using Scala.
object HelloWorld {

    def main(args : Array[String]) {

      println("Hello, world!")


If you are coming from java, this program can be compared with the below java "Hello World" program.
public class HelloWorld {

     public static void main(String[] args) {

          System.out.println("Hello, World!");



Both Java, & scala requires main method with String arguments, in order to execute the program. The method definition is slightly different in Scala, when compared to Java, as you can see in the above programs. In any application we will have only one public class with a main method. This is conceptually similar to singleton pattern. So in Scala , you can define singleton using object key word.

Executing Above Program In REPL :

REPL (Read Evaluate Print Loop) is an interactive shell where Scala expressions are interpreted interactively. Assuming that you have already installed scala software in your local machine. Here is the output of the above program executed in REPL.

You can also execute the above program as shell script. Below is the script code, that can be executed in bash shell.

#! /bin/sh

exec scala "$0" "$@"


object HelloWorld {

    def main(args : Array[String]) {
       println("Hello, World! "+args.toList)




can be run directly from the command shell:
> ./script.sh
 How To Compile And Execute Scala Program Just Like Java ?

Similar to Java, Scala has the command scalac to compile one (or more) Scala source file(s) and generate Java bytecode which can be executed on any standard JVM. Both javac, scalac compilers works similarly.

> scalac HelloWorld.scala

By default scalac generates the class files into the current working directory. If you want to specify different directory use the '-d' option.

> scalac -d bin HelloWorld.scala

The command "scala" executes the generated bytecode with the appropriate options provided.

> scala HelloWorld

you can also specify command options , such as the -classpath (or -cp) option :

> scala -classpath bin HelloWorld

Another Approach To Print Hello World In Scala :

object HelloWorld2 extends Application {

    println("Hello, World!")


If an object in Scala, extends Application, then all the statements contained in that object will be executed.

That's All. Enjoy Scala Coding. 


Post a Comment

Note: only a member of this blog may post a comment.