Search code examples
kotlinsharedpreferences

Why sharedPreferences.getString may return null?


1) In the bellow picture I want to understand why sharedPreferences.getString() give me type mismatch that it may return null but sharedPreferences.getBoolean() and sharedPreferences.getInt() doesn't give me type mismatch warning?

2) What about defValue, doesn't it main that if it didn't find SharedPrefKey.App_LANGUAGE it will return en? so it can't return null, wright?

enter image description here


Solution

  • Check out the implementation for getString in the SharedPreferences interface.

    @Nullable
    String getString(String key, @Nullable String defValue);
    

    The method itself is marked as @Nullable which means that it can return null. Now if you look at the defValue parameter, you'll notice it's also marked as @Nullable meaning you don't have to pass in a default. If it's the case that you're looking for a string preference that doesn't exist and don't pass in a default value, then that will return null.

    int getInt(String key, int defValue);
    boolean getBoolean(String key, boolean defValue);
    

    If you look at the implementation of getInt and getBoolean above, you can tell that you have to pass in a default value, so it will never be null. This is why you see the difference in nullability with the examples you posted.