How to Flatmap collection inside Pair in Kotlin

Viewed 2889

In this example I have to classes.

Order(selections: List<Selection>, discount: Double, ...)
Selection(productId: Long, price: Double, ...)

I then keep collection of Order that I want to calculate prices afterward which need to use Selection's price and Order's discount. How can I do this?

I try to do the following but it doesn't seem to be possible.

val orderList: List<Order> = loadFromDB()

orderList.map { Pair(it.selections, it.discount) }  
.flatMap { /* Here I want to get list of Pair of selection from all orders with discount. */}

Once I have Collection of Pair(Selection, discount) then I can continue calculating further. Is that possible to do in this form? Do I need to separate the chain?

2 Answers

An alternate syntax to @D3xter's answer using a bit more Kotlin sugar:

1    orderList
2        .flatMap { order ->
3            order.selections.map { selection ->
4                order.discount to selection.price } 
5        .map { (discount, price) -> ... }

This makes use of two Kotlin features:

  1. to infix operator on line 4 which is a "factory function" for Pair
  2. Destructuring the pair on line 5 directly into named variables discount and price
Related