如何在Kotlin中向listof()函数添加项?

alen0pnh  于 6个月前  发布在  Kotlin
关注(0)|答案(2)|浏览(79)

我有一个带有Coordinate(latitude,longitude)数据类的listof()变量,例如,我是如何初始化它的:

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()函数添加项呢?
谢谢

qfe3c7zg

qfe3c7zg1#

listOf返回不可变的List<out Coordinate>
为了能够向列表中添加项,可以使用mutableListOf<Coordinate>示例化它

iqxoj9l9

iqxoj9l92#

.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))
    }
  }
}

字符串

相关问题