Design Converter
Education
Last updated on Aug 2, 2024
Last updated on May 6, 2024
Are you new to the Kotlin realm?
Do you see terms like 'Kotlin Singleton' surfacing quite frequently and wonder what it exactly means?
Don’t worry!
Here is your go-to guide for unraveling the world of Kotlin Singleton.
The Kotlin Singleton is quite the rage in the developer community for the advantages it brings. Welcome to this technical blog where our central character is Kotlin Singleton. Here, you shall get answers to questions like "What is a Kotlin Singleton?", "Why should one understand Kotlin Singleton?", and much more.
A Kotlin Singleton ensures only one instance of a class exists. It also provides a global point of access, ensuring simplicity and preventing the creation of multiple instances.
So, without further ado, let's sail forward to understand more about Singleton in Kotlin.
A Singleton in Kotlin is an object-oriented way that allows a class to 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.
A Singleton Kotlin class serves as a fort that controls access to an object while ensuring that no other object can instantiate its copy of 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.
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:
1class 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 holds a paramount position when it comes to the Kotlin Singleton class. Hold your breath as this may come as a 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:
1Object 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.
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'.
1object MySingleton { 2 var variableName:String = "Hello! I am a Singleton Object in Kotlin" 3 fun accessMe() = "Accessing: $variableName" 4} 5 6fun main() { 7 println(MySingleton.accessMe()) // Outputs: Accessing: Hello! I am a Singleton Object in Kotlin 8}
Isn't it amazing that a Singleton object can be this simple in Kotlin?
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.
1object MySingleton { 2 init { 3 println("Singleton class invoked.") 4 } 5 var variableName:String = "I am a Singleton Object in Kotlin" 6} 7 8fun 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.
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:
1class 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 } 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.
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:
1class 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 } 16 } 17} 18 19fun 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.
Through this blog post, we unlocked the secrets of Kotlin Singleton and discussed:
The definition and functionality of Singleton in Kotlin.
In-depth details of Kotlin Singleton class.
The unique role of the Object keyword in Kotlin Singleton.
The nature and application of Kotlin Singleton Object.
How a typical Singleton class in Kotlin is created with a private constructor.
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.
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!
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.