Vladyslav Baidak
Vladyslav Baidak

Reputation: 229

Kotlin Assign Delegate After Variable Declaration

So, basically I have a class:

class App : Application() {

    lateinit var prefs: SharedPreferences

}

Now, I want to add a delegated property:

var isInitialized: Boolean by prefs.boolean()

The problem is that this, isInitialized property must be initialized lazily since I'm using Android Dagger2 framework, which performs injection after App creation (during calling onCreate() method):

class App : Application() {

    lateinit var prefs: SharedPreferences

    var isInitialized: Boolean = false

    override fun onCreate() {
        super.onCreate()
        // how can I assign a delegate to isInitialized?

    }

}

I would like it to be done either via:

Is there any way of doing this?

Thanks!

Upvotes: 0

Views: 881

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170733

You could do it with an indirection:

class DoubleDelegate<R, T>(var realDelegate: ReadWriteProperty<R, T> = /* some default */) : ReadWriteProperty<R, T> by realDelegate

then

val isInitializedDelegate = DoubleDelegate<App, Boolean>()

var isInitialized: Boolean by isInitializedDelegate 

override fun onCreate() {
    super.onCreate()
    isInitializedDelegate.realDelegate = prefs.boolean()
}

Somehow I don't think this is actually a good idea.

Upvotes: 1

Sasi Kumar
Sasi Kumar

Reputation: 13348

Use Lazy

From the document Lazy Gets the lazily initialized value of the current Lazy instance. Once the value was initialized it must not change during the rest of lifetime of this Lazy instance.

Application class

val prefs: Prefs by lazy {
 App.prefs!!
 }

 class App : Application() {
 companion object {
 var prefs: Prefs? = null
 }

override fun onCreate() {
prefs = Prefs(applicationContext)
super.onCreate()
}
}

your data model class should be like this

class Prefs (context: Context) {
val PREFS_FILENAME = "com.teamtreehouse.colorsarefun.prefs"
val IsInitialized = "isInitialized"
val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, 0);
var initialized: Boolean
get() = prefs. getBoolean(IsInitialized, false)
set(value) = prefs.edit(). putBoolean(IsInitialized, value).apply()
}

then use Activity or fragment

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val initialized = prefs.initialized //getvalue
selectvalue(false)// set value

}

  private fun selectvalue(value: Boolean) {
   prefs.initialized = value
  }
}

more details refer this example SharedPreferences Easy with Kotlin

Upvotes: 0

Related Questions