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

第 16 章 函数接口 函数接口

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

在 Java 中,我们使用接口来指定定义某些功能的代码和需要这些功能的代码之间的契约。 这些接口将双方结合在一起,这会使我们的软件更难维护。 函数类型如何帮助解决这个问题?

如果 可以的话,请想象一下,你需要从正在编写的代码中发送电子邮件。现在只需这样做,而不需要接收邮件,也不需要列出已发送的邮件,只需启动并忘记。

描述电子邮件的代码非常简单:

data class Email(
    val to: EmailAddress,
    val from: EmailAddress,
    val subject: String,
    val body: String
)

给定Email ,客户端代码希望调用最简单的函数来发送,即

fun send(email: Email) {
    ...
}

当然,当我们实现这个功能时,我们会发现要真正发送电子邮件,我们还需要各种其他信息。 不是电子邮件本身的信息,而是关于如何发送电子邮件的配置。 比如发送服务器的主机名和安全证书--所有这些你的非技术亲戚都不知道的东西,但你需要为他们的新电脑进行设置。 我们将在sendEmail 中添加三个额外参数,以代替所有这些配置:

fun sendEmail(
    email: Email,
    serverAddress: InetAddress,
    username: String,
    password: String
) {
    ...
}

作为客户端,事情就变得不那么方便了。 我们想要发送电子邮件的每一个地方都必须知道这个配置;我们将把它从代码库的顶层传递到底层。 通过将细节隐藏在全局变量中来解决这个问题,效果还不错,直到我们发现单元测试套件的每次运行都会发送 50 封电子邮件!一定有更好的方法来隐藏这些琐碎的细节。

面向对象的封装

面向对象语言 对这一问题有现成的解决方案--对象可以封装数据:

class EmailSender(
    private val serverAddress: InetAddress,
    private val username: String,
    private val password: String
) {
    fun send(email: Email) {
        sendEmail(
            email,
            serverAddress,
            username,
            password
        )
    }
}

现在,当我们要发送电子邮件时,我们需要访问EmailSender (而不是静态函数)。一旦我们有了EmailSender ,我们调用的就不是函数,而是方法,我们不需要告诉方法所有琐碎的细节,因为它已经知道了;这些细节是它的类的字段:

// Where we know the configuration
val sender: EmailSender = EmailSender(
    inetAddress("smtp.travelator.com"),
    "username",
    "password"
)

// Where we send the message
fun sendThanks() {
    sender.send(
        Email(
            to = parse("support@internationalrescue.org"),
            from = parse("support@travelator.com"),
            subject = "Thanks for your help" ...
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