Chapter 14. Accumulating Objects to Transformations

Java programs usually rely heavily on mutable state because it is so arduous in Java to define value types and transform values, even with the Streams API. What is the best way to translate Java code that relies upon mutable objects and side effects to Kotlin code that transforms immutable values?

Calculating with Accumulator Parameters

One of the most important things our travelers want to know is how much their adventures will cost. International travel makes this rather complicated. A trip will incur costs in multiple currencies as it wends its way across borders, but the traveler wants to be able to compare overall costs to make decisions about routes and where to stay. So Travelator summarizes costs by local currency and the traveler’s preferred currency, and then shows the overall total in the preferred currency. It does this using the CostSummary and CostSummaryCalculator classes. Let’s take a look at how they are used, and then we’ll look at their implementation.

The Itinerary class has an operation for summarizing its costs with a CostSummary​Cal⁠culator. It is used like this:

val fx: ExchangeRates = ...
val userCurrency = ...
val calculator = CostSummaryCalculator(userCurrency, fx) 1

fun costSummary(i: Itinerary): CostSummary {
    i.addCostsTo(calculator) 
    return calculator.summarise() 
}

Get Java to Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.