This section of the Kotlin Koans tutorial continued onward with Kotlin’s collection API enhancement. The challenge in this section use to total the price of all products a customer purchased. Here is the code
fun Customer.getTotalOrderPrice(): Double { // Return the sum of prices of all products that a customer has ordered. // Note: a customer may order the same product for several times. return orders.sumByDouble { it.products.sumByDouble { it.price } } }
The collection API in Kotlin has a sumByDouble method, which takes a lambda expression. The lambda let’s developers chain function calls. In this case, each Customer had a collection of Products in each Order. To get the price of all Products ordered, I needed the sum of the price of all products in a order. This was easy enough to do because I just made a nested call to sumByDouble on it.products and then told it to sum on it.price.
Here is Java code that solves the same problem.
public static double getTotalOrderPrice(Customer customer){ return customer .getOrders() .stream() .mapToDouble( order -> order.getProducts() .stream() .mapToDouble(Product::getPrice) .sum()) .sum(); }
You can click here to see Part 18
One thought on “Kotlin Koans—Part 19”