Liz Douglass

Posts Tagged ‘singleton objects

Scala Singleton Objects

with one comment

There are two types of singleton objects in scala – companion objects and standalone objects. According to Programming in Scala:

“A singleton object definition looks like a class definition, except instead of the keyword class you use the keyword object… When a singleton object shares the same name with a class, it is called that class’s companion object. You must define both the class and its companion object in the same source file. The class is called the companion class of the singleton object. A class and its companion object can access each other’s private members… A singleton object that does not share the same name with a companion class is called a standalone object. You can use standalone objects for many purposes, including collecting related utility methods together, or defining an entry point to a Scala application”

Whilst I like the pattern of separating what would otherwise be static methods in Java into companion objects, I do find at times that they are a bit unintuitive, specifically in these two cases:

1. As shown in the brief example below it’s necessary to include the name of the companion object when invoking one of its methods, even from within the companion class. Coming from a Java background and therefore not being used to having static methods in a separate object, I’ve found that I’ve on occasion forgotten to do this.

class Foo {

  def bar {
    println(Foo.createName)
  }

}

object Foo {

  def createName: String = Math.random.toString

}

Programming in Scala has an example with a slightly neater way of handling this situation – including an import statement at the top of the companion class:

class Foo {
  import Foo._

  def bar {
    println(createName)
  }

}

object Foo {

  def createName: String = Math.random.toString

}

2. Along a similar line, I have also been caught out trying to invoke the methods of a companion object via an instance of the associated companion class. The code below shows how its still necessary to call the createName method from the Foo companion object even though we have the someFoo Foo instance:

class Foo {

  def bar(name: String){
    println(name)
  }

}

object Foo {

  def createName: String = Math.random.toString

}

class Consumer {

  val someFoo = new Foo
  someFoo.bar(Foo.createName)

}

Written by lizdouglass

December 15, 2010 at 9:24 am

Posted in Uncategorized

Tagged with ,