Labels

Thursday, April 14, 2022

Singleton Object in Scala (Class -37)

Singleton Object is another Class of only One instance which can be created using keyword called ‘object’. An object that can exist without a class is a singleton object. It objects keyword is used to define it.

 A Scala object is a singleton object that is accessible to any Scala code that has visibility of that object definition. The term singleton here refers to the fact that there is a single instance of the object definition within the virtual machine executing the Scala program. This is guaranteed by the language itself and does not require any additional programmer intervention.


Objects can • extend classes, • mix in traits, • define methods and functions • as well as properties (both vals and vars). • But they cannot define constructors.

Every program needs a point from where the execution starts. In Object Oriented Programming Scala (OOPS) classes need objects to get executed. But the main() method needs to be executed first to call other members of the class.

For executing the main() method in Scala many object-oriented programming languages use the static keyword but it Scala programming language there is no static keyword. That is why in Scala we use a singleton object that defines the main method.


Always use Main syntax “def main(args:Array[String]){“ method for execution in class.



Features of singleton object

  • Created using object keyword.
  • Members are global i.e. can be called from anywhere in the program.
  • Creation of instance is not possible in case of singleton objects.
  • Inheritance is allowed, i.e. it can extend class and traits.
  • To excess members of Singleton object, we will use the singleton object's name dot members name.
    For example, Singleton_objname.member;

No comments:

Post a Comment