Singleton and companion objects

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:

Figure 3: Object creation in Scala
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.157.190