提问人:Tommy 提问时间:11/4/2023 更新时间:11/4/2023 访问量:63
如何在 Kotlin 中将项目添加到 listof() 函数?
How to add an item to a listof() function in Kotlin?
问:
我有一个带有数据类的listof()变量,例如,这是我初始化它的方式:Coordinate(latitude,longitude)
var coordinate = listof<Coordinate>()
我想通过从 Firebase 数据库中检索多边形的每个标记来添加纬度和经度,例如:
val databaseReference = FirebaseDatabase.getInstance().getReference("polygon").child("coordinate")
databaseReference.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val numberOfCoor = snapshot.childrenCount.toInt()
var i = 1
for (n in i until numberOfCoor + 1) {
val latitude = snapshot.child("coordinate$i")
.child("latitude").getValue().toString().toDouble()
val longitude = snapshot.child("coordinate$i")
.child("longitude").getValue().toString().toDouble()
coordinate.plus(Coordinate(longitude, latitude))
}
}
override fun onCancelled(error: DatabaseError) {
}
})
所以从上面的代码中可以看出,我使用coordinate.plus(Coordinate(longitude, latitude))
但是当我下载这个GeoJSON文件时,坐标没有纬度和经度。
那么如何在 Kotlin 中将项目添加到 listof() 函数中呢?
谢谢。
答:
2赞
Vlad Guriev
11/4/2023
#1
listOf
返回一个不可变的List<out Coordinate>
为了能够将项目添加到列表中,您可以使用以下命令对其进行实例化mutableListOf<Coordinate>
2赞
ΓDΛ
11/4/2023
#2
该方法不会修改原始列表。或者,您可以使用 ..plus
.add
使用 .您可以添加和删除元素。mutablelist
var coordinate = mutableListOf<Coordinate>()
// ...
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val numberOfCoor = snapshot.childrenCount.toInt()
var i = 1
for (n in i until numberOfCoor + 1) {
val latitude = snapshot.child("coordinate$i")
.child("latitude").getValue().toString().toDouble()
val longitude = snapshot.child("coordinate$i")
.child("longitude").getValue().toString().toDouble()
coordinate.add(Coordinate(longitude, latitude))
}
}
}
评论