The term singleton refers to a class that contains only one instance during the application life cycle. This instance is globally available for all functions and classes. Compared to Java or other programming languages, Kotlin provides an easier way to create a singleton class using the object keyword:
object singletonClassName {
properties
fun function(){
function body
}
}
The singleton class is similar to other normal classes; it contains properties and functions and can implement interfaces. However, there are a few things that make this class unique:
- The object keyword is used for class declaration
- We cannot create an instance of this class
- We cannot declare a constructor with this class
Let's take an example of a Button class that has one property and one function:
object MyButton {
var count = 0
fun clickMe() {
...