Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin. Unchecked cast: Any? to HashMap<String?, String?>?

Tags:

android

kotlin

I want to get HashMap<String?, String?>? from firebaseDatabase:

override fun onDataChange(dataSnapshot: DataSnapshot) {
    val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?  // todo !!!
    if (users != null) {
        if (!users.containsKey(userUid)) {
            users[userUid] = userName
        }
    }
}

This code works but Android Studio shows a warning on a 2nd line:

 Unchecked cast: Any? to HashMap<String?, String?>?

How to fix this in a proper way?

like image 718
Rainmaker Avatar asked Mar 10 '18 12:03

Rainmaker


2 Answers

You can use @Suppress("UNCHECKED_CAST")

(eg)

@Suppress("UNCHECKED_CAST")
val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?
like image 59
Narasimman P Avatar answered Oct 18 '22 02:10

Narasimman P


The approach with GenericTypeIndicator works, thank you @leoderprofi

    val ti = object : GenericTypeIndicator<HashMap<String?, String?>?>() {}
    //...
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val users: HashMap<String?, String?>? = dataSnapshot.getValue(ti)
        if (users != null) {
            if (!users.containsKey(userUid)) {
                users[userUid] = userName
            }
        }
    }
like image 5
Rainmaker Avatar answered Oct 18 '22 01:10

Rainmaker