Objects as singletons
There are no static members or classes in Scala. Once you feel the need to create a static member, for example a static method or a class that is going to have only one instance, you should create an object. Yes, up until now, almost all the time we have been creating an object that extends the App
trait so that we don't have to define the main
method. This is the entry point to our application. So, it's also obvious that when we mention object
, we don't mean an instance of any class; rather, an object
in Scala has a different meaning.
An object, just like classes, is a container for functions and values. The reason why we may want to declare an object is so we can define utility methods for any particular type, or sometimes define JSON formatters and similar use cases. Let's take another look at how we can define an object:
object CountryUtil { }
Looks like we just created an object. Nothing fancy, just an object
keyword along with the name of the object. We know...