Skip to Content
Java 到 Kotlin
book

Java 到 Kotlin

by Duncan McGregor, Nat Pryce
May 2025
Intermediate to advanced
424 pages
6h 12m
Chinese
O'Reilly Media, Inc.
Content preview from Java 到 Kotlin

第 14 章 积累对象到变换 累积对象到变换

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

Java 程序通常非常依赖可变状态,因为在 Java 中定义值类型和转换值非常困难,即使使用 Streams API 也是如此。 有什么好办法可以将依赖可变对象和副作用的 Java 代码转换为转换不可变值的 Kotlin 代码?

使用累加器参数进行计算

旅行者最想知道的事情之一就是他们的冒险之旅需要花费多少钱。 国际旅行使这一问题变得相当复杂。 旅行在跨越国界的过程中会产生多种货币的费用,但旅行者希望能够比较总体费用,以便决定路线和住宿地点。 因此,Travelator 按当地货币旅行者的首选货币汇总费用,然后以首选货币显示总费用。Travelator 使用CostSummaryCostSummaryCalculator 类来实现这一功能。让我们先看看它们是如何使用的,然后再看看它们的实现。

Itinerary 类有一个用CostSummary​Cal⁠culator 总结其成本的操作。其使用方法如下:

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

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

这里的代码创建了一个CostSummaryCalculator ,其中包含旅客首选的货币和货币汇率来源。

2

这就告诉Itinerary 将其成本添加到计算器中。 作为回应,计算器Itinerary在计算器中添加其要素的成本:沿线行程、住宿和其他收费服务。

这将调用计算器的summarise 方法,以获得所有成本计算后的CostSummary

已经有人将Itinerary 类转换为 Kotlin,但 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

使用 Kotlin 进行 Android 编程

使用 Kotlin 进行 Android 编程

Pierre-Olivier Laurence, Amanda Hinchman-Dominguez, G. Blake Meike, Mike Dunn
Programming with MicroPython

Programming with MicroPython

Nicholas H. Tollervey

Publisher Resources

ISBN: 9798341659209