【发布时间】:2019-02-04 06:54:24
【问题描述】:
在https://try.kotlinlang.org/#/Kotlin%20Koans/Collections/FlatMap/Task.kt
它有使用flatMap和map的示例
似乎两者都在做同样的事情,是否有示例显示使用 flatMap 和 map 的区别?
数据类型:
data class Shop(val name: String, val customers: List<Customer>)
data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}
data class Order(val products: List<Product>, val isDelivered: Boolean)
data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}
data class City(val name: String) {
override fun toString() = name
}
样本:
fun Shop.getCitiesCustomersAreFrom(): Set<City> =
customers.map { it.city }.toSet()
// would it be same with customers.flatMap { it.city }.toSet() ?
val Customer.orderedProducts: Set<Product> get() {
return orders.flatMap { it.products }.toSet()
// would it be same with return orders.map { it.products }.toSet()
}
【问题讨论】:
标签: collections kotlin flatmap