Search code examples
androidkotlinsharedpreferences

What's the point of having a default value in sharedPref.getString?


I'm accessing my Android apps SharedPreferences via

private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`

and then attempting to get data from it using

val lat: String = sharedPref.getString("MyKey", "Default")

But this line gives me an error reading "Type mismatch. Required String, found String?"

According to the documentation the second parameter in the getString method says "Value to return if this preference does not exist. This value may be null."

So what's the point of having a default value then if the value can be null? I cannot seem to get the default value to ever be used and the only way I can get my code to work is to use the elvis operator and rewrite my code as:

val lat: String = sharedPref.getString("MyKey", "Default") ?: "Default"

Which looks ugly. Am I crazy? What am I missing?


Solution

  • Consider this in a such way: Every String preference in SharedPreferences can exist or not and can be null or not. So the code

    val lat: String = sharedPref.getString("MyKey", "Default") ?: "Not Set"
    

    will return:

    • Default if the preference with this Key doesn't exists (means there is no mapping for this Key)
    • Not Set if the preference exists, but is null (mapping Key to null created)
    • any other value if the preference exists and the value of the mapping isn't null.

    Update

    Apparently, SharedPreferences are much less smart I thought it was. Having this code internally:

    String v = (String)mMap.get(key);
    return v != null ? v : defValue;
    

    it will return null only if we'll pass null as a default value (and there were no value saved). This means we actually don't need an elvis option and we will not get "Not Set" value. This method returns nullable value, just because it allows you to pass nullable as a default value.