11 Singleton objects

After reading this lesson, you will be able to

  • Implement a singleton object
  • Use objects as executable programs
  • Define static functions in a companion object
  • Create factory methods using the apply function

The essence of object-oriented programming is representing elements of the real world using classes that describe their behavior through methods. In specific scenarios, such as configurations and main entry points, you need to instantiate a coding element at most once; you usually call it singleton. In Scala, you can create singletons using objects elegantly and concisely. You are also encouraged to clearly distinguish between static and non-static methods; the non-static ones act on a specific instance of a class, while ...

Get Get Programming with Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.