Rainmaker
Rainmaker

Reputation: 11110

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

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?

Upvotes: 7

Views: 14697

Answers (2)

Narasimman P
Narasimman P

Reputation: 105

You can use @Suppress("UNCHECKED_CAST")

(eg)

@Suppress("UNCHECKED_CAST")
val users: HashMap<String?, String?>? = dataSnapshot.value as HashMap<String?, String?>?

Upvotes: 7

Rainmaker
Rainmaker

Reputation: 11110

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

Upvotes: 6

Related Questions