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.
Creating 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 {
...