Scala Classes, Objects & Singleton Objects

Previously we have learned about Scala Programming Language, Variable Declaration and Method Declaration. Now we’ll have a closer look at the Scala classes and Objects. We’ll also learn about creating Singleton objects in Scala.

Similar to Java, classes in Scala describes the objects. Classes may contain reference variables, methods as well as constructors.
Lets have various examples of classes in Scala,

In case you want to write any code in constructor, you can write in block of class after class declaration statement.

You can also define multiple constructors using this keyword.

Singleton object

Singleton objects are objects which has one and only one instance. In Scala, you cannot have static variable or methods in your class. Instead of defining methods or variables static, you can create a singleton object by defining methods and variables using object keyword.

If you have observed in above examples the class name and object (singleton) name are same. Such classes are referred as Companion Classes and objects are referred as Companion objects.

Leave a Reply

Your email address will not be published. Required fields are marked *