Objects and Singletons
We'll cover the following
The Singleton
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.