科特林。未经检查的演员阵容:任何?到HashMap <string?,string?=“”>?

时间:2018-03-10 12:37:41

标签: android kotlin

我想从HashMap<String?, String?>?获取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
        }
    }
}

此代码有效,但Android Studio在第二行显示警告:

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

如何以正确的方式解决这个问题?

2 个答案:

答案 0 :(得分:1)

GenericTypeIndicator的方法有效,谢谢@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
            }
        }
    }

答案 1 :(得分:0)

您可以使用@Suppress("UNCHECKED_CAST")

(例如)

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