映射对象时,如果某个属性为null,则忽略元素



我正在使用以下函数将网络对象映射到域对象。

映射功能

fun getLocationLocalModel(input: LocationSearchResponse): List<Location> {
return input.locations.map { location ->
return@map location.bbox?.let {
Location(
name = location.name,
countryCode = location.countryCode,
north = location.bbox.north,
south = location.bbox.south,
west = location.bbox.west,
east = location.bbox.east
)
}
}.filterNotNull()
}

网络DTO

data class LocationSearchResponse(
@SerializedName("geonames")
val locations: List<Location>
)
data class Location(val bbox: Bbox?, val countryCode: String, val countryName: String,
val geonameId: Int, val lat: String, val lng: String, val name: String)

领域模型

@Parcelize
data class Location(val name: String, val countryCode: String, val north: Double, val south: Double, val east: Double, val west: Double) : Parcelable

我想要的是忽略bbox为null的对象,这样它们就不会被添加到位置的结果列表中。这个函数有效,但必须有更好/更简单的方法。如有任何帮助,我们将不胜感激。

正如Animesh在评论中提到的那样,只需将语句更改为mapNotNull即可,无需使用return@语法:

return input.locations.mapNotNull { loc ->
loc.bbox?.let { bbox ->
Location(loc.name, loc.countryCode, bbox.north, bbox.south, bbox.west, bbox.east)
}
}

或者,您可以先进行筛选,然后使用!!来取消引用:

return input.locations
.filter { it.bbox != null }
.map { loc->
val bbox = loc.bbox!!
Location(loc.name, loc.countryCode, bbox.north, bbox.south, bbox.west, bbox.east)
}

就我个人而言,前者似乎更容易阅读。

最新更新