In Kotlin, creating a singleton object is very easy using the ‘object‘ keyword. An object is a single instance of a class, which is created lazily when accessed for the first time.
Here’s an example of creating a singleton object in Kotlin:
object Singleton {
var count = 0
fun incrementCount() {
count++
}
}
In this example, we’ve created a singleton object called ‘Singleton‘. This object has a single property ‘count‘ and a single function ‘incrementCount()‘. The object can be accessed globally and there can only be one instance of it.
To access the property and function of the singleton object, we can use the syntax:
Singleton.count
Singleton.incrementCount()
Since the object is a singleton, we don’t need to create an instance of it to access its properties or functions. The object is lazily created when it is first accessed.
We can also create a companion object which can have access to the private variables and functions of the containing class as well as other functions and variables, without having to create an instance of the class. Here is an example of that:
class MyClass {
private var count = 0
companion object {
fun create(): MyClass {
return MyClass()
}
}
fun incrementCount() {
count++
}
}
In this example, we’ve created a class called ‘MyClass‘ with a private property ‘count‘ and a function ‘incrementCount()‘ that increments ‘count‘. We’ve also created a companion object with a single function ‘create()‘ that creates an instance of ‘MyClass‘.
To access the ‘create()‘ method of the ‘MyClass‘ companion object, we can use the syntax:
val obj = MyClass.create()
Here, we’re creating an instance of ‘MyClass‘ using the ‘create()‘ function of the companion object. Since the companion object is also a singleton, we don’t need to create an instance of it either.