【问题标题】:Filter an array of objects by distance Kotlin按距离过滤对象数组 Kotlin
【发布时间】:2018-06-17 21:51:59
【问题描述】:

我是 Kotlin 的新手,正在尝试将一些 Swift 代码转换为 Kotlin。

这是我的 swift 函数。它过滤掉距离用户超过特定距离的数组对象。

func filterByDistance(_ events:[Event]) -> [Event] {
    let filteredEvents = events.filter { event -> Bool in
        if let lat = event.venue?.location?.latitude,
            let long = event.venue?.location?.longitude,
            let userLocation = UserLocation.shared.location {
            let eventLocation = CLLocation(latitude: lat, longitude: long)
            let distance = eventLocation.distance(from: userLocation)
            let convertedDistance = distance * 0.000621371
            if convertedDistance <= maxDistance {
                return true
            }
        }
        return false
    }
    return filteredEvents
}

以下是我目前使用 Kotlin 得到的结果

fun LatLng.toLocation() = Location(LocationManager.GPS_PROVIDER).also {
        it.latitude = latitude
        it.longitude = longitude
    }

fun filterByDistance(events: Array<Events>): Array<Events> {
    val filteredEvents = events.filter<Events> { event ->
        val lat = event.venue?.location?.latitude
        val long = event.venue?.location?.longitude
        val userLocation = LatLng(latitude, longitude)
        val eventLocation = LatLng(lat, long)
        val distance = eventLocation.toLocation().distanceTo(userLocation.toLocation())
        val convertedDistance = distance * 0.000621371
        if (convertedDistance <= 500) {
            return  true
        } else {
            return false
        }
    }
    return filterEvents(events)
}

我收到一个错误,要求我将返回类型更改为 Bool,但我需要返回一组过滤后的事件。有人可以帮我吗?

编辑:多亏了 JB Nizet,我才得以完成这项工作。我不得不将对象从数组更改为列表。这是工作代码。

fun fetchJson() {
        val url = "URL String"
        val request = Request.Builder().url(url).build()
        val client = OkHttpClient()
        client.newCall(request).enqueue(object:Callback{
            override fun onResponse(call: Call?, response: Response?) {
                val body = response?.body()?.string()
                val gson = GsonBuilder().create()
                val eventss = gson.fromJson(body, Array<Events>::class.java)
                val events = eventss.toList()
                val filteredEvents = filterByDistance(events)
                runOnUiThread {
                    recyclerView.adapter = MainAdaptor(filteredEvents)
                }
            }
            override fun onFailure(call: Call?, e: IOException?) {
                println("failed")
            }
        })
    }



fun LatLng.toLocation() = Location(LocationManager.GPS_PROVIDER).also {
        it.latitude = latitude
        it.longitude = longitude
    }

fun filterByDistance(events: List<Events>): List<Events> {
      val filteredEvents = events.filter { event ->
            val lat = event.venue?.location?.latitude
            val long = event.venue?.location?.longitude
            val userLocation = LatLng(latitude, longitude)
            val eventLocation = LatLng(lat, long)
            val distance = eventLocation.toLocation().distanceTo(userLocation.toLocation())
            val convertedDistance = distance * 0.000621371
            convertedDistance <= maxDistance
        }
        return filteredEvents
  }

如果对任何人有帮助的话,还有班级:

class Events (val type: String,
              val venue: Venue,
              val time: String,
              val name: String,
              val summary: String,
              val activity: String,
              val image_link: String,
              val membership_link: String,
              val description: String
              )

class Venue(val type: String,
            val name: String,
            val address: String,
            val location:Location
)

class Location(val type: String,
               val latitude: Double,
               val longitude: Double)

【问题讨论】:

    标签: arrays swift filter kotlin


    【解决方案1】:

    替换

    if (convertedDistance <= 500) {
        return  true
    } else {
        return false
    }
    

    通过

    convertedDistance <= 500
    

    return filterEvents(events)
    

    通过

    return filteredEvents
    

    有关 lambda 语法的说明,请参阅 https://kotlinlang.org/docs/reference/lambdas.html#lambda-expression-syntax

    我们可以使用限定返回语法从 lambda 显式返回一个值。否则,隐式返回最后一个表达式的值。因此,以下两个sn-ps是等价的:

    ints.filter {
        val shouldFilter = it > 0 
        shouldFilter
    }
    
    
    ints.filter {
        val shouldFilter = it > 0 
        return@filter shouldFilter
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多