Leveraging Kotlin Singleton For Optimal Performance
Leveraging Kotlin Singleton For Optimal Performance
Sign
Resources Join our Sign up
Products Pricing WiseGPT
& Support community in for
free
EDUCATION
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
Kotlin Singleton
A Kotlin Singleton ensures only one instance of a class exists. It also Companion Object
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
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.
1 Object MySingleton {
2 fun show(){}
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 }
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 }
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
16 }
17 }
18
19 fun main(args: Array<String>) {
20 val obj1 = Singleton.getInstance()
21 val obj2 = Singleton.getInstance()
22 }
https://www.dhiwise.com/post/working-with-kotlin-singleton-an-in-depth-understanding 7/9