Thursday, February 7, 2013

My Stint with SCALA - 1

In this blog, instead of trying to put everything that Scala can do, i am trying to put what all i have learnt so far in Scala.

After so many years of love with JAVA, its difficult to give same respect to a new language but good news is that SCALA runs on JVM ( though it can run on .NET platform as well ) and it has simplified many concepts of Java, similar to what Java did for C/C++ concepts.

To start with Scala, it can be downloaded from As it runs on JVM, so  Java Runtime environment is a must for Scala.

One downloaded and extracted, add <scala-home>/bin to the PATH. To check if the scala is running type below command in console. Something similar should be the result, depending upon the version which is installed:

Scala Version Test

All Scala files are stored with .scala format. Unlike Java, a file name can be different than the class name.
So lets start with the first Hello World ! program in Scala.


object HelloWorld {
  def main(args : Array[String]){
    println("HEllo World!!")


Above code looks somewhat similar to HelloWorld in Java. Lets see the details,

First of all, instead of defining a class ( which is the building block in Java ), we are creating a object, object is also a class but a Singleton class in Scala. So we are creating a singleton object. Its worth noticing that defining singleton class in Scala is very easy compared to Java where we have to do much more to make a class Singleton.

After that we are defining main method, which is same as we do in Java to run a standalone class.

In Scala, method definition is recognized with the keyword def, which is followed by name of method. Similar to Java, main method in Scala also takes Array of String as argument.

Input parameter is defined as args: Array[String] which is Scala way to define the variable. args is name of variable and after colon (:) is the type of variable. Notice the way Array of String is defined which is Array[String] as compared to String[] in Java. Array is also a class in class in Scala.

Last we are printing the Hello World using println method, which is similar to System.out.println in Java.

Running Scala

In order to run above class, like Java, Classpath should be set for class. Then run below command to execute:

scala HelloWorld.scala

Output would be as printed in program:

HEllo World!!

Scala share many similarities with Java, still its a different language as one would need to write very less code  for same problem statement.

No comments:

Post a Comment