Creating singletons in Kotlin
A singleton class is a class that can have only one instance/object of that class at a time. The concept is to restrict instantiation of objects to a certain number. In this recipe, we will explore singletons in Kotlin.
Getting ready
I'll be using Android Studio 3 to write code.
How to do it…
Follow these steps to create singletons in Kotlin:
- Kotlin does not have static members or variables, so for declaring static members of a class, we use
companion object
. Check out this example:
class SomeClass { companion object { var intro = "I am some class. Pleased to meet you!" fun infoIntro(): String { return "I am some class. Pleased to meet you!" } } }
- Accessing the members and methods of
companion
object of the preceding class is the same as we would do for any static members or methods:
var x = SomeClass.intro toast(SomeClass.infoIntro())
- Now what if we want a singleton class, that is, the class with only one object/instance...