Thanks, Miki, for your comment. I think your understanding is correct. It will always return the first created instance.
Technically, I think the code should throw an exception if the requested singleton name (parameter) is different from the first originally created.
The example is to demonstrate sometimes we can't just use object keyword, especially you need an additional parameter. Maybe this example is not a good one. :)
Whether it is common or not to give parameters to singleton, I'm not sure, but database creation is pretty common to be used as singleton. See below example. It doesn't have a constructor parameter (although it can). But, it requires passing in context to create database.
abstract class ArticlesDatabase : RoomDatabase() {
protected abstract val dao: ArticlesDao
companion object {
@Volatile
private lateinit var instance: ArticlesDatabase
fun getInstance(context: Context): ArticlesDatabase
{
synchronized(this) {
if (!::instance.isInitialized) {
instance = Room.databaseBuilder(
context.applicationContext,
ArticlesDatabase::class.java,
"articles.db")
.fallbackToDestructiveMigration()
.build()
}
return instance
}
}
}
}
Great writing, Vincent.
I have 0 knowledge in Kotlin, as I speak in Java, Python and a little Javascript, but I like to extend my view, so I deciced to learn a little bit about Kotlin and read your article. ๐
I have one question too. I have seen many singletons during my life, but I have never seen one which has a constructor, except when using dependency injection.
I see one problem with it. If you really call the instance method from multiple places and pass different parameters (name), then I would expect to get a singleton with the name I specified, but in reality I will get a singleton with a name which was specified in the first call of the instance method.
Am I missing something? Is this common in Kotlin to give parameters to singletons?