Android Developers
Published in

Android Developers

The one and only object

Kotlin Vocabulary

What is a Singleton?

Singleton is a design pattern which ensures that a class has only one instance and provides a global point of access to the object. The Singleton pattern is particularly useful for objects which need to be shared between different parts in your app and for resources that are expensive to create.

Singleton in Java

To guarantee that a class has only one instance, you need to control how the object is created. To create a class with only one instance, make the constructor private and create a publicly accessible static reference of the object. While doing this, you don’t really want to create the Singleton at startup since Singletons are used for objects which are expensive to create. To achieve this, provide a static method which checks if the object is created. The method must return the previously created instance or call the constructor and return the instance.

Singleton in Kotlin

Now, let’s take a look at Kotlin. Kotlin doesn’t have static methods or fields so how can we create a Singleton in Kotlin?

companion object

companion object is similar to object. companion object is always declared in a class and their properties can be accessed by using the host object. The companion object doesn’t require a name. If the companion object has a name, the caller can access the members using the companion object’s name.

Object Expressions

So far we’ve seen the object keyword used in object declarations. object keyword can be used in object expressions as well. When used as an expression, object keyword helps you to create anonymous objects and anonymous inner classes.

--

--

Articles on modern tools and resources to help you build experiences that people love, faster and easier, across every Android device.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store