Kotlin Singleton / getInstance

Apr 20, 2018

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_PASSWORDApp.DATABASE_VERSIONApp.isPro = trueApp.isProSku("pro")// instance is initialized when accessedApp.moshiStringListAdapter.toJson(mutableListOf("Hello", "World"))// first initializationApp.getCrypto("hello")// subsequent getApp.getCrypto()

Option 2: Default instance

class AppHelper {    companion object {        val instance: AppHelper by lazy { AppHelper() }    }    fun run() {        ...    }}
AppHelper.instance.run()

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.