1

I try to read data from Firestore directly on MyClass format. It works fine when I read variable by variable but I wish to read directly the whole class. When doing this:

docRef.get().addOnSuccessListener { documentSnapshot ->
            (this.application as MyApp).value = documentSnapshot.toObject<MyClass>()
        }

I have this error

Type mismatch: inferred type is MyClass? but MyClass was expected

Any idea?

Programmer_3
  • 522
  • 5
  • 18
Dav
  • 19
  • 4

1 Answers1

3

It complains about nullability of class MyClass.

? after the class name means it should be nullable. Compare MyClass? and MyClass.

From the docs the method signature is:

public T toObject (Class<T> valueType)

And it

Returns the contents of the document converted to a POJO or null if the document doesn't exist.

Kotlin considers it as non-null-safe. You can explicitly specify it by !! if you are certain about it being non-null:

(this.application as MyApp).value = documentSnapshot.toObject<MyClass>()!!

Be careful though, it can lead to NPE and is not considered as best practice.

Or as a better solution, you can make value of class MyApp nullable by specifying value: MyClass?.

Evgeny Mamaev
  • 1,237
  • 1
  • 14
  • 31