The Singleton Design Pattern, discussed in Design PatternsElements of Reusable Object-Oriented Software: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, Boston, MA, 1995, 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 complex cases, where you want to define an abstraction, you may create classes. In this section we’ll focus on objects, how to create them, and how to make use of singletons.

Anonymous objects with object expressions

If you want an object, then you should have an object—no fluff, no ceremony, no tax. Kotlin object expressions are like JavaScript objects and Anonymous Types in C#, although they’re also useful to create instances of anonymous classes, like in Java.

In its most basic form, an object expression is the keyword object followed by a block {}. Such a trivial object expression is limited in use but not entirely purposeless. Suppose we want to represent a few pieces of data related to a circle. One option would be to create a Circle class, but that may be overkill. Another option is to keep around multiple local variables, but that doesn’t give us a sense these are closely related values. Object expression can help here, as in this example:

Get hands-on with 1200+ tech skills courses.