Wednesday, September 2, 2009

Beginning Scala - Part 9: Singleton in Scala

The singleton pattern is one of the easiest patterns (at least to understand), but ended up not so easy to implement in imperative languages like Java & C#! Scala has this concept built into the language, without the complications. Here's how it looks:
object A extends B {
}
There you go! That's singleton for you in Scala :). The keyword object does everything for you.

Beginning Scala - Part 8: Any, package, abstract, Unit, extends & override

Any
Just as Object is the root of all objects in java, Any is the root of all objects in Scala. It is the basic object unit, in scala, from which all other objects are derived.

Package
In Scala, package definition looks like so:
package shape {

// All class definitions and methods and functions go in here.

   abstract class Z {
     def greet() : Unit
   }

   class A extends Z{
     override greet)() = println("A here!")
   }

   class B extends Z{
     override greet() = println("B here!")
   }

   def aMethod = {
   }
}
Unit in Scala is like void in Java. Abstract classes are denoted by the keyword abstract and all methods in an abstract class are automatically abstract. The extend keywords behaves similarly to its Java equivalent, and the override keyword is a means of overriding the default implementation and providing a new one.

Thursday, August 27, 2009

Beginning Scala - Part 7: import, def & seq

import
The scala equivalent of java's import keyword is the same "import". However, the wildcard * used in java is replaced by _ in scala. Here's how an import statement looks like:
import scala.io._

def
This defines a function and looks like so:
def sum(in: Seq[String]) = {
   // The body of the function goes here


}
This defines a function that takes one argument, a sequence of string. In scala, it is not mandatory to indicate the return type. The compiler does it for you. However, it is a good practice to provide it. The body of a function goes in after the '='. It may be enclosed in parentheses '{' '}'. There is no return in the body of the function, and as per the rules, the last evaluated expression is the returned entity. Note: In scala function declaration, the name of the argument comes first, followed by a ":" and then comes the type of the argument. As per the functional programming paradigm, functions have no side-effects, meaning, it returns the same value no matter what, and more importantly, it does not mutate or change the values/state of any other entity/variables.

Seq[String]
Identifies an entity which is a sequence (collection) of String.

Beginning Scala - Part 6: Hello World

and now ... the customary "Hello World" version of Scala:
scala> println("Hello World!!!")
Hello World!!!
Notice, Scala code need not be terminated by a semi-colon (;). You can type this in the interactive session or save in it HelloWorld.scala. The scripts are executed with the commad scala whereas classes are compiled with scalac. The latter creates JVM class files. The file extension for scala programs is .scala.

The println is part of scala's Predef, predefined stuff automatically part of every program, just like java.lang in Java.

Beginning Scala - Part 5: Immutability

This concept is derived from mathematics, where x = a + b, means what it is and cannot be overridden or given a new value, like x = c + d. The same concept is carried forward into functional programming. So, what good does it do?

The biggest contribution of immutability is scalability. Since they are immutable, there are no locks or synchronization to deal with! Anyone, who has done decent amount of programming will acknowledge to the fact that it is among the toughest part of programming and prone to errors and inconsistencies! Since, there are no locks, there are no overheads (time) associated with obtaining, releasing or queueing for locks. 

Hence, it also makes the application faster! It also makes the code less complicated and more predictable and gives the ability to write code that is more intuitive to write, which usually results in an intuitive end-user application experience.

Beginning Scala - Part 4: val(read-only) and var(read-write)


If we try and do the following, we get an error:
scala> res3 = res3 + 2
:6: error: reassignment to val
res3 = res3 + 2

This is because the entity res3 or for that matter res0, res1 ... resN are all values and not variables. Variables as the name suggests are entities that can vary over a period of time. Values on the other hand, don't! They remain constant, just like a mathematical equation, like x = a + b. Values are like final variables in java. They are immutable. Hence the error. Simply put, val's are read-only entities, whereas var's are read-write. 


This brings us to the first nuance of functional programming, Immutability. In a pure functional programming language all data structures are immutable. Since Scala is both a functional and imperative language, they have provided the additional keyword 'var' which permits mutabilty, and as we'll learn has its place. 

So why is this concept of Immutability there in functional programming?

Beginning Scala - Part 3: Let's Begin

Type the following:
scala> 1 + 1
res0: Int = 2

scala> 2 * 2
res1: Int = 4

scala> 4 / 2
res2: Int = 2
These snippets are executed interactively. Notice the feedback the interpreter gives res0, res1 and res2. This means the result of the expression are stored in them along with their types, in this case Int. For example, we can do the following too:
scala> 2 * res0
res3: Int = 4

Beginning Scala - Part 2: Installing

You can get the binaries from here. It requires JDK 1.5 or higher. The latest version as of now is 2.7.5. The sdk comes with scalac (scala compiler, just like javac), scala (a REPL interactive session) and host of other executables. We will be using these two mostly.
Once installed, typing scala will lead you to a REPL (Read-Eval-Print-Loop) interactive session:
Welcome to Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.5.0_19).
Type in expressions to have them evaluated.
Type :help for more information.

scala>
You can type your short scripts or code snippets here. But, as the code size increases, we use a programming editor and save the file and use scalac to compile to program to Java bytecodes, just as we do in Java.

Beginning Scala - Part 1: Functional & Object Oriented Programming Language

Scala is a general purpose programming language, which successfully integrates the functional and object-oriented programming paradigms together in one language. It requires some learning of functional programming paradigm for those coming from Java or C# or other languages steeped in OOP. It was designed and implemented by Martin Odersky and his team of researchers at the EPFL.

There are lot of concepts to learn and through this blog I will document my progress. 

Scala is statically typed, object-oriented, functional, extensible and interoperates with both Java & .NET.