I don't understand why Android Studio is not able to tell that, although SharedPreferences declares the defValue of getString as @Nullable, the current value is actually not null!

The result of the following call:

  myFunction(getSharedPreferences().getString(MY_SETTING_NAME.name(), "This string is not null"))

will trigger a warning:

 Argument might be null

How can it be? Since defValue is actually not null and we know it...

1 Answers

ianhanniballake On

The Android framework does not use Kotlin contracts and cannot change the @Nullable annotation on the return value based on whether the defValue you pass is null or not.

As an alternative, you should consider using Kotlin's elvis operator and writing code such as:

myFunction(getSharedPreferences().getString(MY_SETTING_NAME.name(), null)
    ?: "This string is not null")

Which correctly evaluates as non-null.