Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-13

AuthorDave Leeds

No description

Tags
No tags
Publish Year: 2025
Language: 英文
File Format: PDF
File Size: 13.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

speak() call site function call receiver fiona1 != fiona2 calculate { it - 5.0 } when ( tempe ratur e) farmer.greet(animal) The fun way to learn Kotlin programming, one concept at a time! Kotlin: Written and Illustrated by Dave Leeds
(This page has no text content)
Kotlin: An Illustrated Guide Written and Illustrated by Dave Leeds For more about Kotlin from Dave Leeds, visit https://typealias.com.
Kotlin: An Illustrated Guide Copyright ©2025 TypeAlias Studios LLC The author has aimed for excellence when writing, illustrating, and preparing this book, but makes no expressed or implied warranty of any kind. No representation is made as to the accuracy, completeness, currentness, suitability, or validity of its information. The author does not assume and hereby disclaims any liability to any party for any errors, omissions, losses, injuries, or damages in connection with or arising out of the use of the information or code herein. All content of this book is provided on an as-is basis. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the author is aware of a trademark claim, the designations have been printed in initial caps or all caps. Android™, Android robot logo, YouTube® and YouTube logo are trademarks of Google LLC. GitHub® is a registered trademark of GitHub, Inc. JetBrains® and IntelliJ IDEA® are registered trademarks of JetBrains s.r.o. Oracle, Java®, JavaScript®, JVM® and JDK® are registered trademarks of Oracle and/or its affiliates. UML® is a registered trademark of Object Management Group, Inc. in the United States and/or other countries. IntelliJ IDEA screenshots: Copyright © 2025 JetBrains s.r.o., used with permission. IntelliJ IDEA and the IntelliJ logo are trademarks of JetBrains s.r.o. The color theme used in code listings is based on the Darcula theme, by Konstantin Bulenkov. The author is not affiliated with JetBrains®, the sponsors and developers of the Kotlin programming language. Version 1.0.0
i Table of Contents Preface Who Is This Book For? ........................................................................................................................................................... ix How to Read This Book ......................................................................................................................................................... ix Source Code for This Book .................................................................................................................................................. ix Acknowledgments Acknowledgments ................................................................................................................................................................. xi Chapter 1 • Variables, Expressions, and Types Introduction to Variables ......................................................................................................................................................3 Expressions and Statements ...............................................................................................................................................7 Types: Different Kinds of Values .........................................................................................................................................9 Other Types ............................................................................................................................................................................ 11 Summary ................................................................................................................................................................................. 12 Chapter 2 • Functions Introduction to Functions ................................................................................................................................................. 15 Removing Duplication with Functions ......................................................................................................................... 16 Function Basics ...................................................................................................................................................................... 17 Functions with More Than One Parameter ................................................................................................................. 21 Named Arguments .............................................................................................................................................................. 22 Default Arguments .............................................................................................................................................................. 23 Expression Bodies and Block Bodies ............................................................................................................................. 25 Functions without a Result ............................................................................................................................................... 27 The main() function ............................................................................................................................................................. 28 Printing to the Screen ......................................................................................................................................................... 29
Summary ................................................................................................................................................................................. 31 Chapter 3 • Conditionals: When and If Goldilocks and the Three Branches ............................................................................................................................... 35 Introduction to when in Kotlin ........................................................................................................................................ 36 if Expressions ......................................................................................................................................................................... 42 Summary ................................................................................................................................................................................. 45 Chapter 4 • Classes, Objects, and Packages Putting Variables and Functions Together .................................................................................................................. 49 Defining a Class ..................................................................................................................................................................... 50 Objects ..................................................................................................................................................................................... 52 Everything is an Object ...................................................................................................................................................... 60 Single-Instance Objects ..................................................................................................................................................... 62 Grouping into Packages ..................................................................................................................................................... 64 Summary ................................................................................................................................................................................. 70 Chapter 5 • Enum Classes Creating an Enum Class ..................................................................................................................................................... 74 Using an Enum Class ........................................................................................................................................................... 74 Using Enum Classes with when Expressions .............................................................................................................. 75 Adding Properties and Functions to Enum Classes ................................................................................................. 76 Built-In Properties ................................................................................................................................................................ 78 Summary ................................................................................................................................................................................. 79 Chapter 6 • Nulls and Null Safety Introduction to Nulls ........................................................................................................................................................... 83 Compile Time and Runtime .............................................................................................................................................. 87 How Nullable and Non-Nullable Types are Related ................................................................................................. 88 Using Conditionals to Check for null ............................................................................................................................. 92 Using the Elvis Operator to Provide a Default Value ................................................................................................ 94 Using the Not-Null Assertion Operator to Insist that a Value is Present ........................................................... 96 Kotlin: An Illustrated Guideii
When should I use the not-null assertion operator? ............................................................................................... 98 Using the Safe-Call Operator to Invoke Functions and Properties ..................................................................... 98 Summary ...............................................................................................................................................................................101 Chapter 7 • Lambdas and Function References Bert’s Snips & Clips .............................................................................................................................................................105 Introduction to Function Types .....................................................................................................................................107 Introduction to Lambdas .................................................................................................................................................113 The Implicit it parameter .................................................................................................................................................115 Lambdas and Higher-Order Functions .......................................................................................................................116 Lambdas with Multiple Statements ............................................................................................................................118 Closures .................................................................................................................................................................................119 Summary ...............................................................................................................................................................................121 Chapter 8 • Collections: Lists and Sets Introduction to Lists ..........................................................................................................................................................125 Adding and Removing an Element ..............................................................................................................................127 Loops and Iterations .........................................................................................................................................................133 Collection Operations .......................................................................................................................................................135 Introduction to Sets ...........................................................................................................................................................143 Summary ...............................................................................................................................................................................144 Chapter 9 • Collections: Maps The Right Tool for the Job ...............................................................................................................................................149 Associating Data .................................................................................................................................................................149 Map Fundamentals ............................................................................................................................................................151 Creating a Map from a List ..............................................................................................................................................160 Summary ...............................................................................................................................................................................166 Chapter 10 • Receivers and Extensions Standalone Functions and Object Functions ...........................................................................................................171 They’re Not So Different After All .................................................................................................................................174 iiiTable of Contents
Introduction to Receivers ................................................................................................................................................174 Introduction to Extension Functions ..........................................................................................................................177 Summary ...............................................................................................................................................................................181 Chapter 11 • Scopes and Scope Functions Introduction to Scopes .....................................................................................................................................................185 Scopes and Visibility ..........................................................................................................................................................187 Introduction to Scope Functions ..................................................................................................................................195 Choosing the Most Appropriate Scope Function ...................................................................................................201 Which Kotlin scope function should I use? ...............................................................................................................202 Shadowing Names .............................................................................................................................................................202 Scope Functions and Null Checks ................................................................................................................................205 Summary ...............................................................................................................................................................................206 Chapter 12 • Introduction to Interfaces Sue Starts a Farm ................................................................................................................................................................211 Introducing Interfaces ......................................................................................................................................................215 Subtypes and Supertypes ...............................................................................................................................................218 Casting ...................................................................................................................................................................................221 Multiple Interfaces .............................................................................................................................................................223 Interface Inheritance .........................................................................................................................................................225 Default Implementations ................................................................................................................................................227 Summary ...............................................................................................................................................................................229 Chapter 13 • Introduction to Class Delegation Roger’s Dinner Out ............................................................................................................................................................233 Delegation in Restaurants and Code ..........................................................................................................................233 Manual Delegation ............................................................................................................................................................234 Easy Delegation, the Kotlin Way ...................................................................................................................................239 Multiple Delegates .............................................................................................................................................................240 Overriding a Delegated Call ...........................................................................................................................................241 Kotlin: An Illustrated Guideiv
Managing Conflicts ............................................................................................................................................................242 Delegation for General and Specific Types ...............................................................................................................245 Summary ...............................................................................................................................................................................247 Chapter 14 • Abstract and Open Classes Modeling a Car ....................................................................................................................................................................251 Introduction to Abstract Classes ...................................................................................................................................254 Extending Abstract Classes .............................................................................................................................................254 Inheritance ............................................................................................................................................................................256 Overriding Members .........................................................................................................................................................259 Introduction to Open Classes ........................................................................................................................................262 Getter and Setter Visibility Modifiers ..........................................................................................................................263 Combining Interfaces and Abstract/Open Classes ................................................................................................265 Comparing Interfaces, Abstract Classes, and Open Classes ...............................................................................265 Subclasses and Substitution ..........................................................................................................................................265 Class Hierarchies .................................................................................................................................................................266 The Any Type ........................................................................................................................................................................267 Summary ...............................................................................................................................................................................268 Chapter 15 • Data Classes and Destructuring Overriding equals() ............................................................................................................................................................271 Overriding hashCode() .....................................................................................................................................................276 Overriding toString() .........................................................................................................................................................277 Introduction to Data Classes ..........................................................................................................................................279 Copying Data Classes ........................................................................................................................................................281 Destructuring ......................................................................................................................................................................283 Limitations of Data Classes .............................................................................................................................................289 Summary ...............................................................................................................................................................................291 Chapter 16 • Sealed Types Adding Another Type ........................................................................................................................................................297 vTable of Contents
Introduction to Sealed Types .........................................................................................................................................299 Sealed Classes ......................................................................................................................................................................301 Why Is the sealed Modifier Required At All? .............................................................................................................302 Restrictions of a Sealed Type’s Subtype .....................................................................................................................304 Sealed Types vs Enum Classes .......................................................................................................................................305 Summary ...............................................................................................................................................................................308 Chapter 17 • Handling Runtime Exceptions Problems at Runtime .........................................................................................................................................................311 Catching Exceptions ..........................................................................................................................................................319 Throwing Exceptions ........................................................................................................................................................324 Exception Types ..................................................................................................................................................................325 Handling Multiple Exception Types Differently .......................................................................................................328 Evaluating a Try Expression ............................................................................................................................................330 Try-Catch-Finally .................................................................................................................................................................331 A Functional Approach to Exception Handling .......................................................................................................333 Summary ...............................................................................................................................................................................334 Chapter 18 • Generics Mugs and Beverages .........................................................................................................................................................339 Declared Types, Actual Types, and Assignment Compatibility ..........................................................................342 Introduction to Generic Types .......................................................................................................................................344 Type Parameter Constraints ...........................................................................................................................................347 Generics in Practice ...........................................................................................................................................................349 Generics in the Standard Library ..................................................................................................................................352 Trade-Offs of Generics ......................................................................................................................................................353 Summary ...............................................................................................................................................................................356 Chapter 19 • Generic Variance Covariance ............................................................................................................................................................................359 Contravariance ....................................................................................................................................................................364 Kotlin: An Illustrated Guidevi
What Makes a Subtype a Subtype? ..............................................................................................................................369 Variance Modifiers .............................................................................................................................................................371 Variance on Multiple Type Parameters .......................................................................................................................374 Type Projections .................................................................................................................................................................375 Variance in the Standard Library ..................................................................................................................................381 Summary ...............................................................................................................................................................................382 Chapter 20 • Coroutine Essentials One Thing at a Time… ......................................................................................................................................................385 Coroutines and Concurrency .........................................................................................................................................387 Two Things at a Time… ....................................................................................................................................................397 Two Robots, Two Things at a Time… ...........................................................................................................................402 Cancellations ........................................................................................................................................................................411 Summary ...............................................................................................................................................................................420 Appendix A • How to Run the Code Listings Loading the Sample Code Project ................................................................................................................................423 Creating a Kotlin Project ..................................................................................................................................................424 Other Ways to Write and Run Kotlin Code .................................................................................................................427 Appendix B • Adding Dependencies Adding Dependencies to a Gradle Project ................................................................................................................430 Adding Dependencies to a Maven Project ...............................................................................................................431 Summary ...............................................................................................................................................................................431 Index Index .......................................................................................................................................................................................433 Learn Kotlin programming the fun way! ....................................................................................................................440 viiTable of Contents
Kotlin: An Illustrated Guideviii
ix Preface Who Is This Book For? If you’re interested in learning Kotlin development, this book is for you. Everyone has a unique experience— some readers are new to software development entirely, some are new to Kotlin development, and some are existing Kotlin developers who want a deeper understanding of certain language concepts. My approach in this book is to explain Kotlin programming concepts with simple, tangible, and illustrated examples, so that regardless of your experience level, things will make sense. I do my best to define terms clearly before using them, so that as you read the book, you’ll build upon a solid foundation of existing knowledge. Even if you’re familiar with some of these concepts, my goal is to present them in such a fun and vivid way that you’ll enjoy revisiting them—bringing clarity to any foggy corners you may have wondered about. How to Read This Book This book is written to take you on an adventure, starting with very few expectations of what you already know. I’ve presented the concepts and terms in a particular, cumulative order, so that you shouldn’t need to interrupt your reading with web searches to figure out what different terms mean. I recommend reading the book from front to back, starting with Chapter 1 and progressing through Chapter 20. This book also includes a few optional appendices at the end. If you’re already a developer in the JVM world, you probably already know how to set up your tools, create a project, and add a dependency using Gradle or Maven. If not, these appendices will get you started. Source Code for This Book The code listings in this book are brief and easy to follow, but sometimes it helps to see the surrounding context from previous examples to ensure they run properly. You can find the code listings for this book with their full context online at https://github.com/typealias-studios/kotlin-illustrated-guide.
Kotlin: An Illustrated Guidex
xi Acknowledgments There are so many wonderful people who have motivated and encouraged me while I wrote this book, and I’m deeply grateful for each one of them. My Family First, I’m very thankful to my wife, Elizabeth! She’s been a massive support and encouragement to me at every step along the way. She’s always cheering me on! Thanks to everyone else in my family who has believed in me and encouraged me. (I also appreciate Ninja, our little Miniature Schnauzer, who sat next to me while I wrote most of the book!) My Mentor A huge thank you to Beverly Jamison, who was my mentor for the first decade of my software development career. Another decade has passed since working together, but I learned so much from her, and I wouldn’t be the developer—nor the person—I am today without her guidance and leadership! My Friends Thanks to these friends who have been especially encouraging as I’ve been writing about Kotlin: Beebe, Butler, Ensor, Fleckenstein, Jared, Majtan, McSorley, Pinzur, Rakidzich, and everyone else. The Reviewers Thanks so much to everyone who reviewed this book and provided feedback. James Lorenzen has been a constant reviewer for me, providing tons of amazing feedback for this book and other projects of mine throughout the past decade or so. Others who reviewed a significant portion of this book include David Blanc, Louis CAD, Matt McKenna, Björn Michael, Mohit Sarveiya, and Doug Smith.
JetBrains Thanks to the Kotlin team at JetBrains for creating a language that I love using, and to the Kotlin developer advocates at JetBrains, who have encouraged me and cheered me on along the way. The Community I’m very grateful to both Kotlin Weekly and Android Weekly for all the times that they’ve included my articles, chapters, videos, and livestreams in their weekly newsletters. Thanks also to the entire Kotlin community for your kind words of encouragement over the years. You have no idea how much that has meant to me! And finally, thanks to you for purchasing this book and supporting my work! Kotlin: An Illustrated Guidexii
Variables, Expressions, and Types Kotlin: An Illustrated Guide Chapter 1
So you want to be a Kotlin developer? You’ve come to the right place! This book will take you through the fundamentals of Kotlin, gently introducing you to the most important concepts of the language in order to help you become a proficient Kotlin developer. Even if you’re a seasoned pro, it’s important to know the fundamentals in order to establish a solid foundation of understanding so that you can be as effective as possible. Your adventure starts here in Chapter 1, where we’ll cover the basics of variables, expressions, and types. Let’s get to it! 2 Kotlin: An Illustrated Guide
Introduction to Variables This is a circle. In ancient Greece, Archimedes discovered how to measure the length around a circle, known as its circumference. You probably remember the equation from junior high geometry class. The circumference of a circle is equal to 2 times π times the radius of the circle. In the equation above, the letter r isn’t a number itself. It’s a letter that represents the radius—the distance between the center of the circle and the edge of the circle. We call r a variable, because the radius can vary, depending on the size of the circle. In other words, the variable r isn’t a number; it’s kind of like a bucket that holds a number—any number. Circumference = 2 r circumference r r 3Chapter 1 • Variables, Expressions, and Types
Variables aren’t just for algebra and geometry. They’re also used all the time in programming, where they serve the same purpose: holding numbers—and other things! In Kotlin, you can create a variable and put a number into it like this. This code is actually doing two things on one line. 1. Declaration - When we write var r, we’re declaring a new variable named r. Declaring a variable is kind of like creating a bucket. 2. Assignment - When we write r = 5.2, we’re assigning the value of 5.2 to the variable r. In other words, we’re putting the number 5.2 into the bucket. Let’s break down the three main parts of this line of code. In this code: • var is a keyword that tells Kotlin to create a new variable. • r is the name of the variable. You might also hear this referred to as the variable’s identifier. • The number 5.2 is the value that is being assigned. r 5.2 var r = 5.2 variable name keyword value var r = 5.2 assignment declaration Listing 1.1 - Creating a variable in Kotlin. var r = 5.2 4 Kotlin: An Illustrated Guide