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

2019-08-19 08:02发布

问题:

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?

回答1:

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