Wednesday, February 4, 2015
Scala Traits defines object types by providing signature of the supported methods. This tutorial provides a quick introduction to Scala Traits.

Some key points on Scala Traits.
  1. Scala Traits are like interfaces in Java. 
  2. Scala Traits can have default implementations for certain methods unlike Java interfaces. 
  3. Scala Traits don't have any constructor parameters.
  4. Scala class inherits only one super class but supports mixing multiple traits.
Let us look into a simple example to understand Scala Traits. Scala Traits are defined using the keyword trait and looks like a class definition. In this example we define a trait called Vehicle which can have both abstract methods and concrete methods.

trait Vehicle {
  // Abstract methods
  def make() : String
  def speed() : Int
  // Concrete methods
  def specs() = { 

Let us write a class which extends the trait Vehicle. Concrete implementation needs to be provided only for the traits abstract methods.

class Car extends Vehicle {
  def make() : String = { "Ford" }
  def speed() : Int = { 150 }

object ScalaTraitsTest {
  def main(args:Array[String]) {
    val c = new Car

This program produces the following output.


Scala Traits and Diamond Problem

For C++ programmers whenever topic of multiple inheritance is discussed the focus is on the topic of diamond problem. Here classes Derived1 and Derived2 inherit from Base and Derived3 inherits from both Derived1 and Derived2. If both Derived1 and Derived2 override a method in Base there is ambiguity in Derived3 on which implementation should be inherited. In C++ developers need to override each conflicted method at the bottom of the diamond to resolve the ambiguity.

Diamond Problem with Multiple Inheritance
Java doesn't support multiple inheritance prior to Java 8 and hence avoid the diamond problem. But in Java 8 with the introduction of default methods on interfaces Java is subject to diamond problem. Again the conflicted method needs to be implemented at the bottom of diamond to resolve ambiguity.

Scala provide a simple solution to resolve the diamond problem by considering the order in which Traits are inherited. The implementation in the super type that is furthest to the right is considered. If the class/ trait inheriting provides a overridden implementation then this is considered.

Let us analyze Scala solution to Diamond problem with an example.
trait Base {
  def print

trait Derived1 extends Base {
  override def print() = { println("I am Derived1") }

trait Derived2 extends Base {
  override def print() = { println("I am Derived2") }

class Derived3 extends Derived1 with Derived2 {

object DiamondTest {
  def main(args:Array[String]) {
    val d = new Derived3
Here the super type Derived2 is farthest to the right and produces the following output.
I am Derived2
If the clsas Derived3 has its own implementation for the method as below.
class Derived3 extends Derived1 with Derived2 {
   override def print() = { println("I am Derived3") }
Output is.
I am Derived3

Proceed to read other Scala Tutorials.
Sunday, February 1, 2015
Scala supports an interesting construct called case classes with the intent of creating immutable objects that can be used in pattern matching. This article provides a quick introduction to Scala case classes with examples.

A case class is created by adding the keyword case before the class definition.

case class Employee

Scala Case Classes can be used to automatically generate boilerplate code in classes that are primarily intended for storing data. Following methods are automatically generated when a class is defined as case class.
  1. apply() method is generated so that there is not need to use "new" keyword for creating a new case class instance.
  2. Getters are automatically defined.
    • Constructor parameters are considered val by default and hence only getters (accessors) are generated. If constructor parameters are declared var setters (mutators) are also automatically generated.
  3. toString() method is generated to simplify logging and debugging.
  4. equals() and hashCode() methods are generated which is used for instance comparison.
  5. unapply() method is generated which extracts/ decomposes the instance into tuples/ parts which enables using case classes in pattern matching.
  6. copy() method is generated which enables cloning an object.
Let us look at a simple case class example to understand the usage of generated methods. By just using the keyword case in class declaration Scala automatically generates all the required boilerplate code.

case class Employee (id: Int, name: String, dept: Int) {

object EmployeeTest {
  def main(args:Array[String]) {
    // "new" keyword is not used as apply() method is generated
    val emp1 = Employee(1, "John", 100);
    // Getter methods for constructor parameters
    println( + " " + + " "  + emp1.dept)
    // Clone the object using copy method
    var emp2 = emp1.copy(2, "Smith")
    // Use toString()
    // Uses equals() and hasCode() for comparison
    if ( emp1 == emp2 )
      println("Objects are same")
      println("Objects are different")

    // Extract information using unapply() method
    emp1 match { case Employee(id, name, dept) => println(id + " " + name + " " + dept) }

This example produces the following output.

1 John 100
Objects are different
1 John 100

Proceed to read other Scala Tutorials.
Saturday, January 17, 2015
Like any object oriented programming language Scala allows to define classes which is the code template for creating objects. This article provides a quick introduction to work with Scala classes.

Scala Classes, Fields and Methods

Scala Class is the extensible static code template that can be initiated into objects at run time. Class definition in Scala can take parameters like constructor arguments. 

Scala Fields are member variables that can be accessed anywhere in the class and provide the initial values. 

Scala Methods are member functions that provide the class behavior.

A simple example of a Scala class. Here employeeId and employeeName are constructor fields, field1 is the class field and print is the class method.

class Employee (var employeeId : Int, var employeeName : String) {

  println("Initializing employee ...")
  var field1: Int = 0

  def print() = {
    println(employeeId + " " + employeeName)
  println("More initialization ...")

To create an instance of a Scala class we use new primitive. In this example, we create an instance of class Employee and invoke a method on the instance.

object EmployeeTest {
  def main(args:Array[String]) {
    val emp = new Employee(5, "John")

Scala Class Constructor

The above Employee example produces the following output.

Initializing employee ...
More initialization ...
5 John

In Scala the primary constructor is different from other programming languages like Java/ C++. The constructor fields, statements/ expressions/ methods in the body of the class form the Scala primary class constructor.

For constructor fields and class fields defined as var (e.g. employeeId, employeeName, field1) Scala automatically generates getters and setters which helps to make the Scala code really concise when compared to Java. If the fields are declared as val Scala generates only the getter method.

For example, getters and setters of a constructor field can be accessed as below.

object EmployeeTest {
  def main(args:Array[String]) {
    val emp = new Employee(5, "John")
    emp.employeeId = 6

Multiple Class Constructors

Classes need to have flexibility to provide various approaches to create objects. This is achieved in Scala using auxiliary constructors. There could be multiple auxiliary constructors and each of them need to have a different signature and has to call one of the previously defined constructors.

Let us look at a variation of the Employee class to understand auxiliary constructors. Auxiliary constructors are defined by creating methods named this. Also one constructor calls another constructor using name this.

class Employee1 (var id : Int, var firstName : String, 
    var lastName: String) {

  def this(id : Int) {
    this(id, "", "")    
  def this(id : Int, fn : String)  {
    this(id, fn, "")    

  def print() = {
    println(id + " " + firstName + " " + lastName)

The Employee class can be created using multiple constructors defined.

object Employee1Test {
  def main(args:Array[String]) {
    val emp1 = new Employee1(5)
    val emp2 = new Employee1(5, "John")
    val emp3 = new Employee1(5, "John", "Smith")

This example produces the following output.
5 John 
5 John Smith

Proceed to read other Scala Tutorials.
Saturday, January 10, 2015
Currying converts a function with multiple arguments into a series of a functions with single argument. This article provides an introduction to Scala Currying Functions.

Scala Currying Functions is often confused with Scala Partially Applied Functions. Both currying and partial application enables creation of derived functions with smaller number of arguments. Key difference is that in currying we get the next single argument function in a series of functions whereas in partial application we get a function with smaller number of arguments.

Let us look at a simple example of curried function.

object ScalaCurryingTest {
  def add(x:Int)(y:Int)(z:Int) : Int = { 
    x + y + z
  def main(args: Array[String]) {
    val curried = add(10) _ 

In this example we define a curried function add with multiple parameter lists. When the curried function is invoked it returns the next single argument function in the series of functions.

Continue to read more Scala Tutorials.
Saturday, December 13, 2014
To invoke functions requires us to specify all the function parameters. Scala provides a construct called Partially Applied Functions where a function invocation can be reused by retaining some of the parameters without the need to type them again. Partial application enables conversion of a function with multiple arguments into one with fewer arguments with some values provided in advance.

Let us look at an example to understand the partially applied functions. Here we have basic function multiply to get the product of two numbers. We create two partially applied functions multiplyBy3 and multiplyBy5. Missing argument is substituted with an _ underscore. 

object PartiallyAppliedFunctionsTest {
  def multiply(x: Int, y: Int) : Int = { x * y }
  // Partially applied functions
  val multiplyBy3 = multiply(_:Int, 3)
  val multiplyBy5 = multiply(_:Int, 5)
  def main(args:Array[String]) {
    println("Partial function multiplyBy3 = " + multiplyBy3(6))
    println("Partial function multiplyBy5 = " + multiplyBy5(6))

This example produces the following output.

Partial function multiplyBy3 = 18
Partial function multiplyBy5 = 30

It is also possible to create a partially applied function where all arguments would be passed during function invocation. For example,

val multiply1 = multiply _

Scala provides the syntactic convenience to use single _ (underscore) in this case.

Continue to read more Scala Tutorials.

Contact Form


Email *

Message *

Back to Top