使用SharedPreferences的edit扩展函数报错,需添加何种正确依赖?
问题描述
参考相关文章实现了基于Kotlin委托的DefaultSharedPrefs对象,代码如下:
var sharedApplicationContext: Context get() = _sharedApplicationContext ?: throw IllegalStateException( "Application context not initialized yet." ) set(value) { _sharedApplicationContext = value } private var _sharedApplicationContext: Context? = null private val PREF_NAME = "pref_name" object DefaultSharedPrefs : SharedPreferences by sharedApplicationContext.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE )
但在使用edit扩展函数定义扩展属性时出现报错:
class Foo { ... private var DefaultSharedPrefs.count: Int get() = getInt("key", 0) set(value) = edit { putInt("key", value) } ... }
已添加依赖implementation "androidx.core.content:1.0.0",但问题依旧,请问遗漏了什么?
解决方案
1. 升级androidx.core依赖版本
androidx.core.content:1.0.0是早期版本,带Lambda参数的edit扩展函数是在后续版本中引入的(最低需1.1.0及以上)。建议升级到稳定的新版依赖,同时注意依赖坐标的标准写法:
implementation "androidx.core:core-ktx:1.12.0"
2. 修正DefaultSharedPrefs的初始化时机
object属于饿汉式初始化,APP启动时就会执行sharedApplicationContext.getSharedPreferences(...),但此时sharedApplicationContext可能还未赋值,会直接抛出异常导致委托对象失效。改成延迟初始化的方式更安全:
object DefaultSharedPrefs { val instance: SharedPreferences by lazy { sharedApplicationContext.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE ) } }
后续通过DefaultSharedPrefs.instance访问,确保第一次调用时sharedApplicationContext已完成初始化。
3. 确认导入edit扩展函数
在使用edit的文件顶部,必须导入对应的扩展函数:
import androidx.core.content.edit
4. 修正扩展属性的定义位置
Kotlin不允许在普通类的内部定义其他对象的扩展属性,需将扩展属性移到顶层作用域或伴生对象/其他对象内部:
// 顶层作用域定义(全局可用) private var DefaultSharedPrefs.count: Int get() = instance.getInt("key", 0) set(value) = instance.edit { putInt("key", value) }
若仅在Foo类内部使用,可放在伴生对象中:
class Foo { companion object { private var DefaultSharedPrefs.count: Int get() = instance.getInt("key", 0) set(value) = instance.edit { putInt("key", value) } } }
内容的提问来源于stack exchange,提问作者Sirop4ik
相关产品推荐
相关产品推荐

