Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Kotlin中创建对内的Flatmap集合_Kotlin_Higher Order Functions_Flatmap - Fatal编程技术网

如何在Kotlin中创建对内的Flatmap集合

如何在Kotlin中创建对内的Flatmap集合,kotlin,higher-order-functions,flatmap,Kotlin,Higher Order Functions,Flatmap,在这个例子中,我必须学习两个类 Order(selections: List<Selection>, discount: Double, ...) Selection(productId: Long, price: Double, ...) 一旦我收集了对(选择、折扣),我就可以继续进一步计算了。 在这种形式下可以这样做吗?是否需要分离链?要获得对的列表,可以执行以下操作: orderList.flatMap { order -> //flatMap joins multip

在这个例子中,我必须学习两个类

Order(selections: List<Selection>, discount: Double, ...)
Selection(productId: Long, price: Double, ...)
一旦我收集了
对(选择、折扣)
,我就可以继续进一步计算了。
在这种形式下可以这样做吗?是否需要分离链?

要获得对的列表,可以执行以下操作:

orderList.flatMap { order -> //flatMap joins multiple lists together into one
    order.selections.map { selection ->    //Map every selection into a Pair<Selection, Discount>
        Pair(selection, order.discount) }
    .map { pair -> /* Do your stuff here */ }
orderList.flatMap{order->//flatMap将多个列表合并为一个
order.selections.map{selection->//将每个选择映射为一对
配对(选择、订购、折扣)}
.map{pair->/*在这里做你的事*/}

对于@D3xter的答案,另一种语法是使用更多的Kotlin sugar:

1    orderList
2        .flatMap { order ->
3            order.selections.map { selection ->
4                order.discount to selection.price } 
5        .map { (discount, price) -> ... }
这利用了Kotlin的两个功能:

  • 第4行的中缀运算符是
    对的“工厂函数”
  • 第5行上的对直接输入命名变量
    折扣
    价格

  • 看起来我真的没有考虑太多。谢谢。
    1    orderList
    2        .flatMap { order ->
    3            order.selections.map { selection ->
    4                order.discount to selection.price } 
    5        .map { (discount, price) -> ... }