我尝试直接以 MyClass 格式从 Firestore 读取数据。当我逐个读取变量时它工作正常,但我希望直接读取整个类。
这样做时:
docRef.get().addOnSuccessListener { documentSnapshot ->
(this.application as MyApp).value = documentSnapshot.toObject<MyClass>()
}
我有这个错误Type mismatch: inferred type is MyClass? but MyClass was expected
任何的想法?
最佳答案
它提示 nullability类(class) MyClass
.?
在类名之后意味着它应该可以为空。比较 MyClass?
和 MyClass
.
来自 docs方法签名是:
public T toObject (Class<T> valueType)
而且它Returns the contents of the document converted to a POJO or null if the document doesn't exist.
Kotlin 认为它是非空安全的。您可以通过
!!
显式指定它如果您确定它是非空的:(this.application as MyApp).value = documentSnapshot.toObject<MyClass>()!!
但要小心,它可能会导致 NPE并且不被视为最佳实践。或者作为更好的解决方案,您可以制作
value
类(class) MyApp
通过指定 value: MyClass?
可以为空.
关于android - 使用 toObject/MyClass 从 Firebase 读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63631461/