Wednesday, October 31, 2012

Objects in Scala

The more I develop in Scala, the more I love it. One of the many things that I love about what Martin did with Scala is to create the "object" construct to easily manage singletons in our applications. Many people frown at singletons and they certainly can be misused. However, there are times when they're the right design for the task at hand, and Scala gives us a way to create singletons in a very clean way.

In Java, you'd most likely implement the singleton design pattern by making the default constructor private and then providing a public static method that returns the sole instance of the class. Well, Scala has no static methods or fields. Instead, we have the "object" construct. With "object", Scala takes care of instantiating a single instance of our object with the features that are defined within the object. Take the following object defined in Scala.

object TemperatureConverter {
    def celsiusToFahrenheit(celsius : Double) = {
        celsius * 9 / 5 + 32
    }
  
    def fahrenheitToCelsius(fahrenheit : Double) = {
        (fahrenheit - 32) * 5 / 9
    }

}

When you need to convert fahrenheit to celsius, you can write this.

TemperatureConverter.fahrenheitToCelsius(82)



Scala takes care of creating the object the first time it's used, so we don't have to worry about it. Scala objects make short work of implementing singletons. This can be very handy when writing utility methods or the case when you need to guarantee that only a single instance of an object exists in your application.

What about when you need to add "static" methods to your class? Since Scala doesn't have "static" methods, we can create a companion object for our class. For example, we might have the following Customer class with a companion object for creating a unique customer number.

class Customer {
    val customerNumber = Customer.getNextCustomerNumber()
    ....
}

object Customer {
    private var uniqueNumber = 0
    private def getNextCustomerNumber() = {
        uniqueNumber += 1
        uniqueNumber
    }
}

No comments:

Post a Comment