Objects and Singletons

The Singleton Design Pattern, discussed in Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95], is one of the easiest to understand and yet one of the most difficult to implement. It turns out that controlling the number of instances of a class isn’t a trivial task—you need to prevent reflective access to constructors, ensure thread safety, and, at the same time, not introduce any overhead to check if an instance exists. By providing support for singletons directly, Kotlin removes the burden of implementing the pattern and the risks of getting it wrong. When you need, you can directly create an object without being forced to first define a class. For simple situations you can use objects, and for more ...

Get Programming Kotlin 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.