我正在通过以下方式访问我的Android应用程序SharedPreferences

private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`

and then attempting to get data from it using

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

但这一行给了我一个错误,读"Type mismatch. Required String, found String?"

根据文档,getString方法中的第二个参数表示"如果此首选项不存在,则返回的值.This value may be null."

那么,如果默认值可以为空,那么有什么意义呢?我似乎无法使用默认值,而让代码正常工作的唯一方法是使用elvis运算符并将代码重写为:

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

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

推荐答案

以这样的方式考虑:

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

将返回:

  • 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)
  • 如果首选项存在并且映射值不是null,则为任何其他value.

Update

显然,SharedPreferences远没有我想的那么聪明.在内部拥有此代码:

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.

Kotlin相关问答推荐

如果一项工作失败,请继续在Kotlin 等待其他工作/子元素完成

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

在Kotlin lambda的参数中如何指定函数类型?

可以在没有导入声明的情况下调用 Kotlin 扩展函数吗?

MyType.()在 Kotlin 中是什么意思?

gradle 如何 Select 以-jvm结尾的库?

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

通用接口继承

如果不为空,则为 builder 设置一个值 - Kotlin

如何从 kotlin 中的数据类访问 val?

如何从 kotlin 函数中 Select 正确的枚举值

JobIntentService 被销毁,当应用程序被销毁时

Kotlin:泛型、反射以及类型 T 和 T:Any 之间的区别

Kotlin 中的 Java Scanner 相当于什么?

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

androidx.core:core-ktx:1.0.0 小部件包丢失

使用 Paging 3 时保存并保留 LazyColumn 滚动位置

Kotlin协程处理错误和实现

如何获取Kotlin中变量的名称?