Cory Robinson
Cory Robinson

Reputation: 5262

Kotlin how to try/catch a cast

I am storing shared preferences value as a HashSet and when retrieving I see the warning about unchecked casting. What is the most simple and what is the safest solution to ensure bug free implementation here?

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)
    }
}

kotlin code example

Upvotes: 0

Views: 979

Answers (3)

tadev
tadev

Reputation: 224

You can try

kotlin.runCatching { }.onFailure {  }

Upvotes: 0

Himanshu Choudhary
Himanshu Choudhary

Reputation: 370

Apart from the try/catch block, you can also safely unwrap it while putting in the model.

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

Upvotes: 3

user13146129
user13146129

Reputation:

You can try this

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

Upvotes: 1

Related Questions