0% found this document useful (0 votes)
32 views7 pages

Leveraging Kotlin Singleton For Optimal Performance

Uploaded by

specsdeveloper13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views7 pages

Leveraging Kotlin Singleton For Optimal Performance

Uploaded by

specsdeveloper13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

Sign
Resources Join our Sign up
Products Pricing WiseGPT
& Support community in for
free

EDUCATION

Working with Kotlin Singleton: An In-


Depth Understanding
Pratik Chothani LAST UPDATED ON AUG 2, 2024
Software Development Executive - II

Are you new to the Kotlin realm? What is a Singleton


in Kotlin?
Do you see terms like 'Kotlin Singleton' surfacing quite frequently and
Deep Dive into Kotlin
wonder what it exactly means? Singleton Class

Don’t worry! The Object


Keyword's Role in
Kotlin Singleton
Here is your go-to guide for unraveling the world of Kotlin Singleton.
Exploring the Kotlin

The Kotlin Singleton is quite the rage in the developer community for Singleton Object

the advantages it brings. Welcome to this technical blog where our Unlocking Kotlin

central character is Kotlin Singleton. Here, you shall get answers to Object Singleton

questions like "What is a Kotlin Singleton?", "Why should one Kotlin Singleton with

understand Kotlin Singleton?", and much more. Private Constructor

Kotlin Singleton
A Kotlin Singleton ensures only one instance of a class exists. It also Companion Object

provides a global point of access, ensuring simplicity and preventing Explored

the creation of multiple instances. Conclusion: Key


Insights about Kotlin

So, without further ado, let's sail forward to understand more about Singleton

Singleton in Kotlin.
Tired
coding all
What is a Singleton in Kotlin? day?
Do it with a
A Singleton in Kotlin is an object-oriented way that allows a class to few clicks.
have only one instance in the runtime environment. That means you
can make a global point of access to the object and keep a check of
the class's lifetime.
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 1/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

A Singleton Kotlin class serves as a fort that controls access to an Harness


object while ensuring that no other object can instantiate its copy of Gen-AI

the object. In other words, it blocks other objects from using the new
keyword with the singleton class.

Now, you may ask how a Singleton class achieves this in Kotlin. It's
primarily made possible through a class with a private constructor.
Let's dive deeper into how this works in the next section.

Deep Dive into Kotlin Singleton


Class
Within the realms of Kotlin for Android development, a Kotlin Singleton
class particularly shines. The singleton class in Kotlin Android
advances with a private constructor mathematically limiting the
number of objects created from the class to exactly 'one'.

Here's a simple Kotlin Singleton class example:

1 class Singleton private constructor(){


2 init {
3 println("Instance is created")
4 }
5
6 companion object {
7 val instance = Singleton()
8 }
9 }

Consequently, because the constructor method is private, you won't


be able to instantiate the class from outside the class. The companion
object declared within is the Singleton object, which is globally
accessible. And Voila! You have your Singleton class in Kotlin Android
ready.

The Object Keyword's Role in


Kotlin Singleton
The 'Object' keyword holds a paramount position when it comes to the
Kotlin Singleton class. Hold your breath as this may come as a
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 2/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

surprise! In Kotlin, Singleton isn't explicitly defined. It's implicitly


declared as an 'Object'. Yes, you read that correctly! The 'Object'
keyword in Kotlin is in itself a Singleton.

Let's have a look at a small code snippet:

1 Object MySingleton {
2 fun show(){}

In this Kotlin Singleton class example, MySingleton is an object, and


show() is its method. Hence, the Kotlin singleton object, MySingleton,
can be accessed globally and comes with a defined lifecycle.

Exploring the Kotlin Singleton


Object
Having discussed the importance of the 'Object' keyword in Kotlin
Singleton, let's delve deeper into the world of the Kotlin Singleton
Object. As mentioned earlier, Singleton Object in Kotlin can be created
by simply declaring an object instead of a class. These are essential
classes with a single instance, hence the term 'Singleton'.

1 object MySingleton {
2 var variableName:String = "Hello! I am a Singleton Object in
3 fun accessMe() = "Accessing: $variableName"
4 }
5
6 fun main() {
7 println(MySingleton.accessMe()) // Outputs: Accessing: Hello
8 }

Isn't it amazing that a Singleton object can be this simple in Kotlin?

Unlocking Kotlin Object


Singleton
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 3/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

A Kotlin Object Singleton bears an interesting characteristic- it's


thread-safe, meaning that the Singleton's instantiation process is safe
to be used across multiple threads. This specific ability empowers it to
perform and deliver even in a multi-threading environment, making
Kotlin Object Singleton truly an asset for developers.

1 object MySingleton {
2 init {
3 println("Singleton class invoked.")
4 }
5 var variableName:String = "I am a Singleton Object in Kotlin
6 }
7
8 fun main() {
9 var a = MySingleton
10 var b = MySingleton
11 a.variableName = "Singleton in Kotlin"
12 println(b.variableName) // Outputs : Singleton in Kotlin
13 println(a.variableName) // Outputs : Singleton in Kotlin
14 println(a) // Outputs : MySingleton@5cad8086
15 println(b) // Outputs : MySingleton@5cad8086
16 }

The above Kotlin Singleton example demonstrates how, even after


multiple references to the Singleton object, all of them point to a single
instance.

Kotlin Singleton with Private


Constructor
The Singleton pattern in Kotlin promotes a single instance of a class
and a global point of access to it. But how do you control the
instantiation of a class? The answer lies in using a 'private constructor'.
A Kotlin Singleton class with a private constructor prevents
instantiation from other classes, thereby enforcing the Singleton
property.

Here’s a look at Kotlin Singleton class with a private constructor:

1 class Singleton private constructor(){


2 init {

https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 4/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

3 println("Singleton class invoked.")


4 }
5
6 companion object {
7 private var INSTANCE: Singleton? = null
8
9 fun getInstance(): Singleton {
10 if (INSTANCE == null) {
11 INSTANCE = Singleton()
12 }
13 return INSTANCE!!
14 }
15 }
16 }

In this Singleton example, Kotlin has a private constructor and an


instance property. The getInstance method ensures that an instance is
created only when it’s null. Once an instance is created, all subsequent
calls return the same instance.

Kotlin Singleton Companion


Object Explored
Now, let's introduce the 'Companion object' keyword in Kotlin.
'Companion object', a globally accessible object, shares its enclosing
class's name space.

Let's take an example of Singleton Kotlin with Companion object for


better understanding:

1 class Singleton private constructor(){


2 init {
3 println("Singleton class invoked.")
4 }
5
6 companion object {
7 private var INSTANCE: Singleton? = null
8
9 fun getInstance(): Singleton? {
10 if (INSTANCE == null) {
11 INSTANCE = Singleton()
12 println("New instance is created.")
13 }
14 return INSTANCE
15 }
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 5/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

16 }
17 }
18
19 fun main(args: Array<String>) {
20 val obj1 = Singleton.getInstance()
21 val obj2 = Singleton.getInstance()
22 }

In this Kotlin Singleton example, a Singleton class with a Companion


object allows the instance creation to happen only once. All
subsequent calls receive the same created instance, enforcing the
Singleton rule.

Conclusion: Key Insights about


Kotlin Singleton
Through this blog post, we unlocked the secrets of Kotlin Singleton
and discussed:

1. The definition and functionality of Singleton in Kotlin.

2. In-depth details of Kotlin Singleton class.

3. The unique role of the Object keyword in Kotlin Singleton.

4. The nature and application of Kotlin Singleton Object.

5. How a typical Singleton class in Kotlin is created with a private


constructor.

6. The purpose and operation of a Companion object.

To recap, Singleton classes are designed in such a way that restricts


the instantiation of a class to a single instance for application-wide
use. Kotlin Singleton eases this process with the use of an 'Object'
keyword providing a built-in Singleton. The Kotlin Singleton class
object is globally accessible, and thread-safe in a multithreading
environment.

A Kotlin Singleton class with a private constructor blocks instance


creation outside the class. Also, Kotlin Singleton companion object
natively provides Singleton pattern implementation, giving associated
benefits of inheritance.
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 6/9
9/19/24, 7:56 PM Leveraging Kotlin Singleton for Optimal Performance

I hope this blog post helps you understand Kotlin Singleton


comprehensively. Whether you are a novice coder or an experienced
Android developer, understanding Kotlin Singleton can significantly
enhance your Kotlin coding skills!

Short on time? Speed things


up with DhiWise!!
Tired of manually designing screens, coding on weekends, and
technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio,


blogging website, social media or admin panel right away. Use our
library of 40+ pre-built free templates to create your first application
using DhiWise.

Frequently asked questions

What is a Singleton in Kotlin Android?

What is the purpose of Companion Objects in Kotlin Singleton?

What is a Kotlin Singleton Object?

https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 7/9

You might also like