在sharedPref.getString中具有默认值有什么意义? [英] What's the point of having a default value in sharedPref.getString?

查看:306
本文介绍了在sharedPref.getString中具有默认值有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过

private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`

,然后尝试使用

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

但是这一行给我一个读取"Type mismatch. Required String, found String?"

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

根据文档,getString方法中的第二个参数表示如果不存在此首选项,则返回值.此值可以为空."

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."

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

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?

推荐答案

以以下方式考虑此问题: SharedPreferences中的每个String首选项可以存在,并且可以是null.这样的代码

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"

将返回:

  • Default如果不存在带有此键的首选项(表示此键没有映射)
  • Not Set(如果存在首选项),但为null(创建了null的映射键)
  • 任何其他value(如果存在首选项并且映射的值不是null).
  • 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.

这篇关于在sharedPref.getString中具有默认值有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆