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

第 21 章 价值的例外情况

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

第 19 章中,我们探讨了 Kotlin 的错误处理策略,以及如何从 Java 中的异常重构为功能性更强的技术。 事实上,大多数代码都会忽略错误,希望它们不会发生。 我们能做得更好吗?

市场部的一个新人开始修改我们在第 20 章中看到的电子表格--那个生成高价值客户评分的电子表格。 我们不知道他们在做什么,但他们不断导出破坏我们解析的文件,然后要求我们解释什么是堆栈跟踪。 这让双方的关系都有点尴尬,所以蛋糕已经开始变少了。 还能有更多的激励吗?

是的,有可能。 我们还被要求编写一个无人值守的作业,这样市场营销人员就可以将文件保存到服务器上,我们会自动编写汇总版本。 如果没有人在循环中解释这些堆栈跟踪,看来我们必须找到一种正确报告错误的方法。

找出可能出错的地方

下面是 代码的原样:

fun Sequence<String>.toHighValueCustomerReport(): Sequence<String> {
    val valuableCustomers = this
        .withoutHeader()
        .map(String::toCustomerData)
        .filter { it.score >= 10 }
        .sortedBy(CustomerData::score)
        .toList()
    return sequenceOf("ID\tName\tSpend") +
        valuableCustomers.map(CustomerData::outputLine) +
        valuableCustomers.summarised()
}

private fun List<CustomerData>.summarised(): String =
    sumByDouble { it.spend }.let { total ->
        "\tTOTAL\t${total.toMoneyString()}"
    }

private fun Sequence<String>.withoutHeader() = drop(1)

internal fun String.toCustomerData(): CustomerData =
    split("\t").let { parts ->
        CustomerData(
            id = parts[0],
            givenName = parts[1],
            familyName = parts[2],
            score = parts[3].toInt(),
            spend = if (parts.size == 4) 0.0 else parts[4].toDouble()
        )
    }

private val CustomerData.outputLine: String
    get() = "$id\t$marketingName\t${spend.toMoneyString()}"

private fun Double.toMoneyString() = this.formattedAs("%#.2f")

private fun Any?.formattedAs(format: String) = String.format(format, this)

private val CustomerData.marketingName: String
    get() = "${familyName.toUpperCase()}, ...
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