jeudi 19 mars 2020

Singleton with constructor parameters in Kotlin

I have created a singleton in Kotlin as follows:

object MySingleton {
    var dataSource: MyDataSource? = null

    fun init(sourceUri: String, setting: String) {
        this.dataSource = MyDataSource(sourceUri).build(setting)
    }

    fun storeData(products: List<Product>) {
        dataSource?.store(products)
    }

    fun getProducts(): List<Product>? {
        return dataSource?.getProducts()
    }
} 

I used init since I couldn't pass parameters to the singleton constructor but I am not sure if this is the proper way in Kotlin. Additionally are there thread safety considerations that I might be missing?

Aucun commentaire:

Enregistrer un commentaire