Kotlin Singleton / getInstance

July 11, 2019

Option 1: Object Declaration

Use kotlin Object declarations.

object App {
    object KEY {
      const val VERIFY_PASSWORD = "1"
    }

    const val DATABASE_VERSION = 1

    var isPro: Boolean = false

    fun isProSku(sku: String): Boolean {
        return sku in listOf("pro", "backer", "patron")
    }

    val moshiStringListAdapter by lazy {
        moshi.adapter<MutableList<String>>(List::class.java)
    }

    @Volatile private var CRYPTO_INSTANCE:Crypto? = null

    fun getCrypto(password: String? = null) : Crypto {
        if (password != null) { // reset
            CRYPTO_INSTANCE = null
        }
        return CRYPTO_INSTANCE ?: synchronized(this) {
            CRYPTO_INSTANCE
                    ?: buildCrypto(password).also {
                        CRYPTO_INSTANCE = it
                    }
        }
    }

    fun buildCrypto(password: String?) : Crypto {
        return ...
    }

Usage.

App.KEY.VERIFY_PASSWORD

App.DATABASE_VERSION

App.isPro = true

App.isProSku("pro")

// instance is initialized when accessed
App.moshiStringListAdapter.toJson(mutableListOf("Hello", "World"))

// first initialization
App.getCrypto("hello")

// subsequent get
App.getCrypto()

Option 2: Default instance

class AppHelper {

    companion object {
        val instance: AppHelper by lazy { AppHelper() }
    }

    fun run() {
        ...
    }
}
AppHelper.instance.run()

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.