【发布时间】:2021-01-27 04:34:38
【问题描述】:
我将共享首选项值存储为HashSet,在检索时我看到有关未经检查的强制转换的警告。什么是最简单和最安全的解决方案,以确保在这里实现无错误?
class TaskListDataManager(private val context: Context) {
fun saveList(taskList: TaskList) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context).edit()
sharedPreferences.putStringSet(taskList.name, taskList.taskList.toHashSet())
sharedPreferences.apply()
}
fun readList(): ArrayList<TaskList> {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val taskLists = sharedPreferences.all.map {
TaskList(it.key, ArrayList(it.value as HashSet<String>))
}
return ArrayList<TaskList>(taskLists)
}
}
【问题讨论】:
-
改用
as?并提供默认值。