Kotlin singleton

A singleton in Kotlin is a design pattern that restricts the instantiation of a class to a single object. This pattern ensures that only one instance of the class is created and provides a global point of access to it.

To create a singleton in Kotlin, you can follow these steps:

  1. Create a class and mark it as object instead of class. This signifies that the class is a singleton.

  2. Define the properties and methods inside the singleton class. These properties and methods can be accessed using the instance of the singleton.

  3. Access the singleton instance using the name of the class followed by . and the name of the property or method.

Here's an example of how to create a singleton in Kotlin:

object Singleton {
    private var count: Int = 0

    fun increment() {
        count++
    }

    fun getCount(): Int {
        return count
    }
}

In this example, the Singleton class is marked as object, making it a singleton. It has a private property count and two methods: increment() and getCount(). The increment() method increments the count property, and the getCount() method returns the current value of count.

To access the singleton instance and its methods, you can use the following code:

Singleton.increment()
println(Singleton.getCount()) // Output: 1

In this code, we call the increment() method of the Singleton class to increment the count property. Then, we use the getCount() method to retrieve the current value of count and print it to the console.

Using this approach, you can ensure that only one instance of the Singleton class is created throughout your Kotlin application.