按距离Kotlin过滤对象数组

时间:2018-01-08 21:37:32

标签: arrays swift filter kotlin

我是Kotlin的新手并试图将一些Swift代码转换为Kotlin。

这是我的快速功能。它过滤掉与用户相距特定距离的数组对象。

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,我能够让这个工作。我不得不将对象从Array更改为List。这是工作代码。

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)

1 个答案:

答案 0 :(得分:4)

替换

convertedDistance <= 500

通过

return filterEvents(events)

return filteredEvents

通过

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


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

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

  

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

{{1}}