Updated April 1, 2023
Introduction to Kotlin Singleton
The singleton is one of the kotlin class, and it is mainly defined with a single instance with the help of a single object it calls wherever it is necessary; the methods are used and triggered the functional logic, so it uses the singleton pattern its one of the software design pattern, and it is mainly used to restrict the class instantiation at only once like network service, database service the instance is accessible through globally both outer and inner sub-classes should always be prevented for to create the each instance with the help of private constructor and static reference it will be implemented.
Syntax of Kotlin Singleton
The kotlin web application uses many default constructors, variables, methods, and keywords to implement and perform the operations. Singleton is one of the features and concepts for implementing the single instance using the singleton design pattern.
object name
{
fun method()
{
--- some logic codes---
}
}
fun main(args:Array<String>)
{
---some codes depends on the requirement—
}
The above codes are the basic syntax for implementing the singleton pattern in the custom method. We can initialise and invoked the singleton in the init() method.
How does Singleton Class work in Kotlin?
The Kotlin classes should have one instance used throughout the application; hence, it comes under the singleton pattern to assure these features in an application. When compared to java in kotlin, we won’t use the new keyword, but in java, each time we want to create the object by using new, it automatically violates the Singleton pattern rules.
When we use a global variable in class that must be the global point of access so the variable has many downsides such that the global variable might be created when the application begins and assuming it to that the specific object using that resources intensively on the application by keeping it from the instantiating multiple objects. So we can approach the class itself to ensure that the single instance is configured through the entire application workflow. In java, it is achieved by using the constructor of the class that might be the private.
We can create the static function that is responsible for tracking the unique instance; it appears as the only instance, then the static function can be called using the class name in anywhere of the application. It does not support and is applicable in java, but we want to use the singleton pattern on the code anyway.
Examples of Kotlin Singleton
Given below are the examples of Kotlin Singleton:
Example #1
Code:
package one;
object first {
init {
println("Your Singleton pattern class is instantiated")
}
var vars = "Have a Nice Day users"
fun fm() {
println(vars)
var fr = 'B'
var thr=41
var second = when(thr) {
1 -> "Its a first user input value"
2 -> "Its a second user input value"
3 -> "Its a third user input value"
4 -> "Its a four user input value"
5 -> "Its a fifth user input value"
6 -> "Its a sixth user input value"
7 -> "Its a seventh user input value"
8 -> "Its a eighth user input value"
9 -> "Its a ninth user input value"
10 -> "Its a tenth user input value"
else -> "Please try again"
}
println("$second")
when(fr){
'V', 'I', 'B', 'G', 'Y', 'O', 'R' -> println("$fr is a character and VIBGYOR characters")
else -> println("$fr is a alphabetical characters")
}
println("Thank you users have a nice day kindly try again please keep and stay with our application $fr")
var yrsage = 18
when(yrsage) {
in 21..150 -> {
val out = 150 - yrsage
println("Your Life age is in $out years")
}
in 1..100 -> println("Thank you users for spending the time with our application please keep and stay with this.")
}
}
}
class Test {
init {
first.fm()
}
}
fun main() {
println("Welcome to my domain its the first example that related to the kotlin singleton")
first.fm()
first.vars = "The singleton pattern to assure that it creates the single object of the class and it is used with throughout the application"
val dem = Test()
}
Output:
In the above example, we performed and implemented the application with some operations. We can call the functions by using the singleton instance.
Example #2
Code:
package one;
interface Second {
val eg: Int
fun exam() : String
fun demo() {
println("Welcome To My Domain its the Second example that related to the kotlin Singleton")
}
}
class Test : Second {
override val eg: Int = 41
override fun exam() = "Have a Nice day users"
}
object secondss {
init {
println("Your Singleton pattern class is instantiated")
}
var vars1 = "Have a Nice Day users"
fun fm() {
println(vars1)
}
}
fun main() {
println("Welcome to my domain its the second example that related to the kotlin singleton")
secondss.fm()
val vars2 = listOf("The singleton","pattern to assure that","it creates the single object", "of the class and it is used", " with throughout","the application")
val res=Test()
for(x in vars2){
println("Thank you users for spending the time with our application $x,$vars2.Singleton { it.toList() }")
}
}
Output:
In the second example, we used classes and interfaces to operate the singleton pattern in the application.
Example #3
Code:
package one;
class Test {
var infos = "Welcome To My Domain its the third example that relates to the kotlin singleton concept"
companion object {
private var xy: Test? = null
val objc: Test
get() {
if (xy == null) {
xy = Test()
}
return xy!!
}
}
}
object Tests {
var infos = "Have a nice day users"
}
fun main(args: Array<String>) {
val eg1 = Test.objc
val eg2 = Test.objc
eg2.infos = "Thanks for spending the time"
println(eg1.infos)
println(eg2.infos)
val eg3 = Tests
val eg4 = Tests
eg4.infos = "Please try again"
println(eg3.infos)
println(eg4.infos)
}
Output:
In the final example, we added an additional companion object for implementing the singleton instance.
Conclusion
In generally, java language concepts are more used and implemented with additional features on the kotlin. Like that Singleton is one of the features which is similar to the java, but additionally, some changes have been made like without new() keyword for object creation etc. However, the rest of the details are the same as Java.
Recommended Articles
This is a guide to Kotlin Singleton. Here we discuss the introduction, syntax, and working of singleton class in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –