July 2017
Intermediate to advanced
796 pages
18h 55m
English
In this subsection, we will see a comparative analysis between the singleton object in Scala and Java. The idea beneath the singleton pattern is to have an implementation that makes sure that only a single instance of a class can exist. Here's an example of the Singleton pattern in Java:
public class DBConnection { private static DBConnection dbInstance; private DBConnection() { } public static DBConnection getInstance() { if (dbInstance == null) { dbInstance = new DBConnection(); } return dbInstance; }}
The Scala object does a similar thing, and it's well taken care of by the compiler. Since there will be only one instance, there is no way for object creation here:
Read now
Unlock full access