Friday, 10 June 2011

Scala - tutorial for newbies (Part 2)

This is the next part of this tutorial. In this session I will tell you how to compile Scala program. I will also let you know some more characteristics of Scala. I hope that you will enjoy it. So lets begin.

Scala is a pure object-oriented language. Every value in Scala is an object and every operation is a method call. So when you type 2 + 3 in your Scala interpreter you are actually invoking a method named "+" defined in class Int. With this little bit of Scala knowledge we will try to write and compile our first Scala program.

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

Please type the above program in your favorite notepad, save it and give it a name, say HelloWorld.scala. Now it is time to compile the program. We will use scalac for this purpose. Execute the below command in your command prompt:

E:\>scalac HelloWorld.scala


This will generate few class files in your current directory. One of them will be HelloWorld.class. It contains a class which can be directly executed using the scala command.

E:\>scala HelloWorld

E:\>Hello World

If you have done little bit of Java programming before then the above program is not difficult to understand. This program consists of a main method that takes the command line arguments, an array of Strings, as parameter. The main method does not return any value. For this reason there is no declaration of return type. It has a single call to the predefined method println with the friendly greeting as argument.

There are few things to notice in the above program. One of them is object declaration. This declaration introduces singleton object - a class with a single instance. So the above declaration declares both a class called HelloWorld and an instance of that class, also called HelloWorld. The next thing to notice - the main method is not declared as static. In Scala, static members (methods or fields) do not exist. You need to declare these members in singleton objects.

By this time I think you know how to define a function. In Scala, function definition starts with def, then the function's name followed by a comma-sperated list of parameters in parentheses.

Lets try the below example in your scala interpreter.

scala> def min(x: Int, y: Int): Int = {
      |   if( x < y ) x
      |   else y
      | }
 min: (x: Int,y: Int)Int

In the above example, the function named min takes two parameters, x and y, both of type Int. You might have noticed that after the closing parenthesis of min's parameters list there is another : Int type annotation. This defines the result type of the min function. In Java, the type of the value returned from a method is its return type. In Scala it is called result type.

Did you see the equals sign in the above function? It says that a function defines an expression that results in a value. Since the above function contains only one statement, you can leave off the curly braces. It can be written like:

scala>def min2(x: Int, y: Int) = if (x < y) x else y
min2: (x: Int,y: Int)Int

There may be situation when you need to define a method that takes no parameter and returns no value. Here is an example:

scala> def sayHelloToScala() = println("Hello Scala")
sayHelloToScala: ()Unit

Scala interpreter has responded with sayHelloToScala: ()Unit. Here sayHelloToScala is the function's name. The empty parentheses indicate that this function does not take any parameter. Unit is the result type of this function. A result type of Unit indicates function does not return any value. It is similar to Java's void type.

With this I stop for now. Thank you very much for reading it. Please give your feedback.

Sunday, 5 June 2011

Scala - tutorial for newbies (Part 1)

Last couple of days I have been thinking of sharing my Scala notes. I am still in learning phase. So any feedback from you will definitely help me to improve my understanding in Scala. There are many articles available in the Internet about Scala. You can read these articles to know more about Scala. In this article I will tell you how to program in Scala. There will be several parts of this tutorial. This is the first part.

A brief introduction:
  • Scala stands for "scalable language".
  • It is both object-oriented and functional.
  • Java compatible - Scala programs compile to JVM bytecode.
  • Scala program can call Java methods, access Java fields, inherit from Java classes, and implement Java interfaces - good news to Java programmers.
  • Scala is concise, less ceremonies.
  • Scala is statically typed.
  • And it is smart Java.

Please download the latest Scala installation from and follow the instructions suitable for your platform. I will use Scala interpreter to try all the examples. So let start writing some Scala code. In my machine I have Scala If you install Scala correctly and enter "scala" at a command prompt then you should see something like this:

Welcome to Scala version (Java HotSpot(TM) Client VM, Java 1.6.0_23)

Type in expressions to have them evaluated.
Type :help for more information.


Probably every programmer in this planet started their programming journey by typing "Hello World!". Let me show you how you can do it in Scala.

scala> println("Hello World!")
Hello World!


I think you probably notice that I haven't typed 'System.out.println("Hello World!")' like Java. I also haven't used any semi-colon ";". By this time I believe you have understood why I said that Scala is concise and less ceremonial. You will see these things more.

Now type 2 + 3.

scala> 2 + 3
res1: Int = 5

In the above figure you will find that an automatic user-defined name "res1" is created and 5 is assigned to it. "res1" means result 1. "Int" indicates integer.

You can use "res1" identifier to do some further programming. For example:

scala> res1 * 4
res2: Int = 20

A new identifier "res2" is created and 20 is assigned to it. The value inside "res1" is not changed, it is still 5. If you type "println(res1)" at your command prompt you will see this.

scala> println(res1)

Now it is time to do some experiment with variables. Scala supports two kinds of variables - val and var. A val can never be reassigned if it is already assigned. So it is similar to final variable in Java. But a var can be reassigned. Try these below examples:

scala> val mymsg = "Hello to Scala"
mymsg: java.lang.String = Hello to Scala

A val variable "mymsg" of type java.lang.String is created and "Hello to Scala" is assigned to it. Now if you try to reassign it with a new value you will get an error message.

scala> mymsg = "Good Morning!!"
<console>:6: error: reassignment to val
mymsg = "Good Morning!!"

Now if you try the same thing with var variable you will not see any error message.

scala> var mymsg2 = "Hello to Scala"
mymsg2: java.lang.String = Hello to Scala

scala> mymsg2 = "Good Morning"
mymsg2: java.lang.String = Good Morning

If you look carefully in above variable related examples you will find that I haven't specified "java.lang.String" anywhere in my variable definition. This shows Scala's ability to figure out types if you leave off - "type inference".

Few more points before I stop this article for today:

Packages in Scala are similar to packages in Java: they partition the global namespace and provide a mechanism for information hiding.

All of Java's primitive types have corresponding classes in the Scala package.

For Example:

scala.Boolean => Java's boolean
scala.Float => Java's float

Once again thank you very much for reading this article. I hope that you enjoy it and like me you will also keep learning Scala. Any feedback is welcome.