【发布时间】: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