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

第 15 章 从封装集合到类型别名 封装集合到类型别名

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

在 Java 中,我们将对象集合封装在类中,以控制突变和添加操作。 在 Kotlin 中,控制突变就不那么重要了,我们可以使用扩展函数来添加操作。 如果没有封装,我们的设计会如何更好,又该如何实现呢?

第 6 章中,我们探讨了 Java 和 Kotlin 在处理集合时的不同之处。 Java 的集合接口与其面向对象的根源一致,从根本上来说是可变型的,而 Kotlin 则将集合视为值类型。 正如我们所看到的,如果我们对共享集合进行变型,就会遇到各种麻烦。 我们可以通过不对共享集合进行变异("Don't Mutate Shared Collections")来避免这种麻烦,但在 Java 中,当addset 方法只是自动完成时,就很难做到这一点了。大多数 Java 代码并没有遵守惯例和纪律,而是明智地选择了更安全的方法,即干脆不共享原始集合。 相反,集合被隐藏在另一个对象中。

例如,这里是 Travelator 中的Route

public class Route {
    private final List<Journey> journeys; 1

    public Route(List<Journey> journeys) {
        this.journeys = journeys; 2
    }

    public int size() { 3
        return journeys.size();
    }

    public Journey get(int index) { 3
        return journeys.get(index);
    }

    public Location getDepartsFrom() { 4
        return get(0).getDepartsFrom();
    }

    public Location getArrivesAt() { 4
        return get(size() - 1).getArrivesAt ...
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