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.introtoast(SomeClass.infoIntro())
- Now what if we want a singleton class, that is, the class with only one object/instance at a time? Brace yourselves, this one is fun. Here's a way to create a singleton class in ...