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.