【问题标题】:Kotlin how to try/catch a castKotlin 如何尝试/捕捉演员表
【发布时间】: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)
    }
}

【问题讨论】:

标签: android kotlin


【解决方案1】:

除了try/catch 块之外,您还可以在放入模型时安全地打开它。

(a.value as? HashSet<String>)?.let {
   TaskList(a.key, ArrayList(it))
}

【讨论】:

  • 谢谢@Himanshu。这是一个优雅的解决方案。
【解决方案2】:

你可以试试这个

try{    
   //code that may throw exception    
}catch(e: SomeException){  
   //code that handles exception  
}finally {  
   // optional finally block  
} 

【讨论】:

  • 你怎么知道错误类型转换会抛出的异常类型?
  • @CoryRobinson e: Exception。它将投射任何类型的exception
【解决方案3】:

你可以试试

kotlin.runCatching { }.onFailure {  }

【讨论】:

  • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2010-11-23
  • 2013-08-04
  • 2014-12-27
相关资源
最近更新 更多