Home > Enterprise >  Why do we need to give default value inside getBoolean() in kotlin?
Why do we need to give default value inside getBoolean() in kotlin?

Time:07-07

I'm trying to put some data whose key: "isLoggedIn" and a value: true inside a shared preference file. I do it this way...

sharedPreferences=getSharedPreferences(getString(R.string.preference_file_name), Context.MODE_PRIVATE)
 fun savePreferences(){
 sharedPreferences.edit().putBoolean("isLoggedIn",true).apply()
}

and then if I want to retreive/store this key-value pair inside a variable it allows me only when I give the second parameter which is a value or defualt value like this.

val isLoggedIn=sharedPreferences.getBoolean("isLoggedIn",false)

The question is why do I have to call the data by its name i.e., "isLoggedIn" and a default value in the getBoolean method instead of just calling it by the name like this code below.. ?

val isLoggedIn=sharedPreferences.getBoolean("isLoggedIn")

CodePudding user response:

There nothing ensure that there is an existing value named "isLoggedIn" in the shared preferences, so you need to provide that default value so incase there is no value named "isLoggedIn", there default value is going to be returned.

You can try it by yourself by getting a boolean of a value that it doesn't exist in your shared preferences and log the result, something like this:

val randomBoolean = sharedPreferences.getBoolean("randomBoolean",false)
Log.d("randomBoolean", "$randomBoolean")

The result of the log will be false, and if you give true as a default value, the result will be true because there is no value named randomBoolean in the shared preferences so the default value is going to be returned.

That's why we need to give a default value.

  • Related