Understanding Kotlin(Singleton) — Part 4

Balaji S B
Proggy Blast
Published in
2 min readDec 15, 2020
Understanding Kotlin Part 4 — Proggy Blast

This article is focusing on how can we create the singleton for the class. This is the series of articles where one can easily learn the kotlin language and can easily apply on android and all kotlin using technologies. If you are new to kotlin please refere previous article Part 3 from here.Here we go…

Singleton Design Pattern :

Singleton is the one of the most using design pattern in the development. There are several design patterns are using and this design pattern is frequently used.

The concept of the singleton design pattern is to maintain the single instance of the class through out the application.

How to create singleton with the help of static declarations ?

In kotlin there is no static keyword. Instead we can declare the static declarations with the help of companion objects.

Here is the sample code to create the singleton with the help of companion object.

Singleton Create with Companion Object

Is this the proper way to create singleton in kotlin ?

Oops..wait..this is the traditional singleton creation like what we do in the java. Instead of static we are using companion objects declarations.

We know kotlin offers to reduce LOC(Lines of the Code). Hence there must be another way kotlin should provide right. Yes that’s true.

Instead of creating the kotlin file as class, we can create with object keyword. Yes that’s it enough. Seriously. That’s the magic happens behind the scenes. You no need to bother about creating the singleton static declaration and comparision. Everything is handle by itself. I think it’s a great rescue.

Here’s the sample code for creating singleton class in kotlin.

Singleton with object keyword

Limitations with object singleton :

Creating a class as singleton, we can create easily with the help of object keyword. But there is one limitation are there. Whatever the class declared as object, it won’t accept the constructor. So we can’t pass the value through the constructor.

And while using dependency injection you can’t use the Inject annotation for object classes.

Conclusion :

Yeah. That’s it. So from this article you come to how to create the singleton properly in kotlin with object keyword with limitations and with companion object. Please do clap (👏) if you like this post. Thanks and Cheers.

Follow us on Instagram, Twitter, Facebook, LinkedIn.

#proggyblast #Kotlin #balajisb Balaji S B Proggy Blast

--

--

Balaji S B
Proggy Blast

Technical Lead @ Happeist Minds Technologies Pvt Ltd