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: