如何在数据类中初始化GeoPoint的默认值 [英] How to initialize default values for GeoPoint in a data class
问题描述
我正在尝试将文档从Firestore转换为对象,但是当我创建数据类时,我不知道如何使用默认值初始化GeoPoint,因为它需要为空的构造函数声明
I'm trying to convert documents to objects from Firestore, but when I create my data class , I dont know how to initialize the GeoPoint with default values as it needs to be declared for an empty constructor
data class MapObj(val geopoint:Geopoint) //--> how to initialize it to get an empty constructor
问题取决于此行
val obj = snapshot.toObject(MapObj::class.java)
谢谢
推荐答案
问题是Firestore SDK找不到MapObj的默认,无参数构造函数.如果Kotlin数据类的所有属性都用val
声明,则没有.对于声明为val
的属性,Kotlin要求在构造函数中指定它们的值,因为它们以后可能无法更改.
The problem is that the Firestore SDK isn't finding a default, no argument constructor for MapObj. Kotlin data classes don't have one if all of their properties are declared with val
. For properties declared val
, Kotlin requires that their values be specified in the constructor, since they can't possibly change afterward.
如果必须从Firestore取回数据类,则必须将其所有属性设置为具有默认值的可选var
,以便Kotlin为其生成一个无参数的构造函数.
If you must get a data class back from Firestore, you will have to make all of its properties optional var
with a default value, so that Kotlin will generate a no-arg constructor for it.
data class MapObj(var geopoint: Geopoint? = null)
这篇关于如何在数据类中初始化GeoPoint的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!