How would you create a singleton with parameter in Kotlin?
How would you create a singleton with parameter in Kotlin?
Here's how you can create a singleton with a parameter in Kotlin:
To create a singleton with a parameter in Kotlin, you can use the object keyword along with a constructor parameter. Here's an example:
class MySingleton(val parameter: String) {
companion object {
@Volatile
private var instance: MySingleton? = null
fun getInstance(parameter: String): MySingleton {
return instance ?: synchronized(this) {
instance ?: MySingleton(parameter).also { instance = it }
}
}
}
// Other singleton methods and properties
}
In this example:
We define a class MySingleton that takes a parameter of type String in its constructor.
Inside the class, we use the companion object to hold the singleton instance.
We declare a @Volatile variable instance of type MySingleton? (nullable `MySing...
middle