Sunday, 9 August 2020

Scala: Hello World using scalac and scala

 In my previous post, I explained how to develop and run a hello world application in Intellij IDEA. In this post, I am going to explain how to develop, compile the application using a scala compiler (scalac) and run the application using ‘scala’ command.

Step 1: Create HelloWorld.scala file.

 

HelloWorld.scala
/*
Below snippet creates Singleton Object
*/
object HelloWorld{

	def main(args: Array[String]): Unit =  {
		print("Hello World")
	}
}

Step 2: Compile HelloWorld.scala file by executing below command.

scalac HelloWorld.scala

$scalac HelloWorld.scala 
$
$ls
HelloWorld$.class	HelloWorld.class	HelloWorld.scala

Compilation generates .class file.

 

Step 3: Execute HelloWorld application by executing the below command.

scala HelloWorld

$scala HelloWorld
Hello World

Let’s decompile HelloWorld.class and see how the generated java code looks like.

 

Explanation

object HelloWorld

‘object’ keyword is used to create singleton object. Right now, you just understand that, main method is the entry point to the Scala application, you should keep main method in singleton object defined using ‘object’ keyword. I will explain more details of object keyword later.

  

HelloWorld$.class decompiled code looks like below.

import scala.Predef$;

public final class HelloWorld$ {
  public static final HelloWorld$ MODULE$ = new HelloWorld$();
  
  public void main(String[] args) {
    Predef$.MODULE$.print("Hello World");
  }
}

HelloWorld.class decompiled code looks like below.

import scala.reflect.ScalaSignature;

public final class HelloWorld {
  public static void main(String[] paramArrayOfString) {
    HelloWorld$.MODULE$.main(paramArrayOfString);
  }
}



Previous                                                    Next                                                    Home

No comments:

Post a Comment