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

后端 未结 4 2017
一个人的身影
一个人的身影 2021-01-17 19:41

I\'m accessing my Android apps SharedPreferences via

private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`

4条回答
  •  醉酒成梦
    2021-01-17 20:22

    It's because kotlin Null-Safety is kick in when reading the following code:

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

    if you visit the SharedPreferences code, you can see the following code:

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

    which is give us a probability to use null as defValue parameter. So, Kotlin try to guard it and give you the matching error:

    "Type mismatch. Required String, found String?"

    You can fix the problem by enabling nullable for your String variable with:

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

    though this against Kotlin type system purpose:

    Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake.

提交回复
热议问题