SayantanRC
SayantanRC

Reputation: 949

Right way to initialise SharedPreference in Kotlin

I am very new to Kotlin. Previously, I used to declare a SharedPreference in an activity as such:

class MainActivity extends AppCompatActivity {
    SharedPreferences main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        main = getSharedPreferences("main", MODE_PRIVATE);
    }
}

This allowed me to use the main instance throughout the class. I would like to achieve a similar functionality. I am currently using lateinit var as such:


class MainActivityKotlin : AppCompatActivity() {
    lateinit var main : SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        main = getSharedPreferences("main", Context.MODE_PRIVATE)
    }
}

But I am not sure if this is the right way of doing it. Also this is a var. As far as I understand, a val is usually recommended where the instance will not change (like in this case, main will not change once initialised). So is this approach correct?

Upvotes: 1

Views: 4099

Answers (2)

Wang
Wang

Reputation: 1038

Indeed, a val is better. You can obtain one with lazy initialisation:

class MainActivityKotlin : AppCompatActivity() {
    private val sharedPrefs by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /* initialisation is removed from here, as it is now lazy */
    }

    fun otherFunction() {
        // the first use of the shared preference will trigger its initialisation
        val prefInt = sharedPrefs.getInt("key", 0)
    }
}

Upvotes: 1

TheWanderer
TheWanderer

Reputation: 17824

Using lateinit is perfectly fine. It's there for this purpose, after all.

There is a slightly cleaner solution you could use, though: lazy-init:

val main by lazy { getSharedPreferences("main", Context.MODE_PRIVATE) }

This only calls getSharedPreferences() when main is first referenced, and then stores that instance. It's similar to how things are done in Java, but you don't need to split lines.

Upvotes: 7

Related Questions