Saturday, November 29, 2014
This article provides a brief introduction to an interesting concept the Scala Companion Object.
  • Scala doesn't have static variables and methods. Scala Companion Object can be visualized as a place holder for all the static variable and method needs of a Scala class. 
  • Scala Companion Object has the same name as an associated Scala class and needs to be specified in the same source file.
  • Scala Companion Object can be used to initialize a class with different set of parameters.
  • Scala Companion Object can be used to implement factory design pattern.
A simple example to introduce Scala Companion Object. Here we have a class Foo and its companion object Foo. Companion object is used to initialize this class with different set of parameters.

class Foo ( x : Int, y : Int ) {
  println(x, y)
}

object Foo {
  
  def get {
   new Foo1(0, 0)
  }
  
  def get ( x : Int ) {
    new Foo1(x, 0)
  }
  
  def get ( x: Int, y : Int ) {
     new Foo1(x, y)
  }
  
  def main(args: Array[String]) {
    val f1 = Foo get
    val f2 = Foo get(10)
    val f3 = Foo get(10, 20)
  }
}

Let us look at a companion object example to implement a Factory design pattern. In this example, we have a class Shape and an object Shape. Here object Shape is the companion object to class Shape. The companion object takes on the factory method responsibilities and creates the requested Shape object.

Scala provides syntactic flexibility to avoid clutter in the code by using apply() method. In the example, instead of an explicit call to apply() method we use Shape("Square") which is a kind of shortcut to call the apply method.

abstract class Shape

private class Square extends Shape { println("Created Square") }
private class Circle extends Shape { println("Created Circle") }
private class Cube extends Shape { println("Created Cube") }

object Shape {
  def apply(shapeType : String) {
    shapeType match {
      case "Square" => new Square
      case "Circle" => new Circle
      case "Cube" => new Cube
    }
  }
  
  def main(args : Array[String]) {
    val sq = Shape("Square")
    val cr = Shape("Circle")
    val cu = Shape("Cube")

    // All of these are same as above
    val sq1 = Shape.apply("Square")
    val sq2 = Shape apply("Square"
    val sq3 = Shape apply "Square"
  }
}

This scala program produces the following output.

Created Square
Created Circle
Created Cube
Created Square
Created Square
Created Square

Proceed to read other Scala Tutorials.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top