记一个谷歌codelab项目中使用的kotlin类的单例写法

class UserPreferencesRepository private constructor(context: Context) {
    companion object {
        @Volatile
        private var INSTANCE: UserPreferencesRepository? = null

        fun getInstance(context: Context): UserPreferencesRepository {
            return INSTANCE ?: synchronized(this) {
                INSTANCE?.let {
                    return it
                }

                val instance = UserPreferencesRepository(context)
                INSTANCE = instance
                instance
            }
        }
    }
}

你可能感兴趣的:(Android,kotlin,kotlin类单例写法)