(This page has no text content)
(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 GuidedKotlin: An Illustrated Guid Copyright ©2020-2024 by Dave Leeds 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. The author is not affiliated with JetBrains®, the sponsors and developers of the Kotlin programming language. Version 0.20.a
Who is this book for? ............................................................................................................................................................vii What’s the current state of this book? ...........................................................................................................................vii Variables, Expressions, and Types Introduction to Variables ................................................................................................................................................... 12 Expressions and Statements ............................................................................................................................................ 16 Types: Different Kinds of Values ...................................................................................................................................... 18 Other Types ............................................................................................................................................................................ 20 Summary ................................................................................................................................................................................. 21 Functions Introduction to Functions ................................................................................................................................................. 24 Removing Duplication with Functions ......................................................................................................................... 25 Function Basics ...................................................................................................................................................................... 26 Functions with More Than One Parameter ................................................................................................................. 29 Named Arguments .............................................................................................................................................................. 31 Default Arguments .............................................................................................................................................................. 31 Expression Bodies and Block Bodies ............................................................................................................................. 34 Functions without a Result ............................................................................................................................................... 36 Summary ................................................................................................................................................................................. 37 Conditionals: When and If Goldilocks and the Three Branches ............................................................................................................................... 40 Introduction to when in Kotlin ........................................................................................................................................ 41 if Expressions ......................................................................................................................................................................... 47 Summary ................................................................................................................................................................................. 50 Introduction to Classes and Objects Putting Variables and Functions Together .................................................................................................................. 53 Defining a Class ..................................................................................................................................................................... 53 Objects ..................................................................................................................................................................................... 55 iTable of Contents Table of Contents
Everything is an Object ...................................................................................................................................................... 64 Summary ................................................................................................................................................................................. 66 Enum Classes Creating an Enum Class ..................................................................................................................................................... 70 Using an Enum Class ........................................................................................................................................................... 70 Using Enum Classes with when Expressions .............................................................................................................. 71 Adding Properties and Functions to Enum Classes ................................................................................................. 72 Built-In Properties ................................................................................................................................................................ 74 Summary ................................................................................................................................................................................. 76 Nulls and Null Safety Introduction to Nulls ........................................................................................................................................................... 79 Compile Time and Runtime .............................................................................................................................................. 82 How Nullable and Non-Nullable Types are Related ................................................................................................. 84 Using Conditionals to Check for null ............................................................................................................................. 87 Using the Elvis Operator to Provide a Default Value ................................................................................................ 89 Using the Not-Null Assertion Operator to Insist that a Value is Present ........................................................... 91 Using the Safe-Call Operator to Invoke Functions and Properties ..................................................................... 93 Summary ................................................................................................................................................................................. 97 Lambdas and Function References Bert’s Snips & Clips .............................................................................................................................................................100 Introduction to Function Types .....................................................................................................................................102 Introduction to Lambdas .................................................................................................................................................108 The Implicit it parameter .................................................................................................................................................110 Lambdas and Higher-Order Functions .......................................................................................................................111 Lambdas with Multiple Statements ............................................................................................................................113 Closures .................................................................................................................................................................................114 Summary ...............................................................................................................................................................................116 Collections: Lists and Sets Introduction to Lists ..........................................................................................................................................................119 Adding and Removing an Element ..............................................................................................................................122 Loops and Iterations .........................................................................................................................................................127 Collection Operations .......................................................................................................................................................129 Introduction to Sets ...........................................................................................................................................................136 Summary ...............................................................................................................................................................................138 Kotlin: An Illustrated Guideii
Collections: Maps The Right Tool for the Job ...............................................................................................................................................141 Associating Data .................................................................................................................................................................141 Map Fundamentals ............................................................................................................................................................143 Creating a Map from a List ..............................................................................................................................................152 Summary ...............................................................................................................................................................................160 Receivers and Extensions Standalone Functions and Object Functions ...........................................................................................................163 They’re Not So Different After All .................................................................................................................................165 Introduction to Receivers ................................................................................................................................................166 Introduction to Extension Functions ..........................................................................................................................169 Summary ...............................................................................................................................................................................173 Scopes and Scope Functions Introduction to Scopes .....................................................................................................................................................176 Scopes and Visibility ..........................................................................................................................................................178 Introduction to Scope Functions ..................................................................................................................................187 Choosing the Most Appropriate Scope Function ...................................................................................................193 Shadowing Names .............................................................................................................................................................194 Scope Functions and Null Checks ................................................................................................................................197 Summary ...............................................................................................................................................................................198 Introduction to Interfaces Sue Starts a Farm ................................................................................................................................................................202 Introducing Interfaces ......................................................................................................................................................207 Subtypes and Supertypes ...............................................................................................................................................209 Casting ...................................................................................................................................................................................212 Multiple Interfaces .............................................................................................................................................................214 Interface Inheritance .........................................................................................................................................................216 Default Implementations ................................................................................................................................................218 Introduction to Class Delegation Delegation in Restaurants and Code ..........................................................................................................................223 Manual Delegation ............................................................................................................................................................223 Easy Delegation, the Kotlin Way ...................................................................................................................................228 Multiple Delegates .............................................................................................................................................................229 Overriding a Delegated Call ...........................................................................................................................................231 iiiTable of Contents
Managing Conflicts ............................................................................................................................................................232 Delegation for General and Specific Types ...............................................................................................................234 Summary ...............................................................................................................................................................................236 Abstract and Open Classes Modeling a Car ....................................................................................................................................................................240 Introduction to Abstract Classes ...................................................................................................................................242 Extending Abstract Classes .............................................................................................................................................243 Inheritance ............................................................................................................................................................................245 Overriding Members .........................................................................................................................................................247 Introduction to Open Classes ........................................................................................................................................251 Getter and Setter Visibility Modifiers ..........................................................................................................................251 Combining Interfaces and Abstract/Open Classes ................................................................................................253 Comparing Interfaces, Abstract Classes, and Open Classes ...............................................................................254 Subclasses and Substitution ..........................................................................................................................................254 Class Hierarchies .................................................................................................................................................................255 The Any Type ........................................................................................................................................................................255 Summary ...............................................................................................................................................................................256 Data Classes and Destructuring Overriding equals() ............................................................................................................................................................259 Overriding hashCode() .....................................................................................................................................................263 Overriding toString() .........................................................................................................................................................265 Introduction to Data Classes ..........................................................................................................................................267 Copying Data Classes ........................................................................................................................................................268 Destructuring ......................................................................................................................................................................270 Limitations of Data Classes .............................................................................................................................................276 Summary ...............................................................................................................................................................................278 Sealed Types Adding Another Type ........................................................................................................................................................283 Introduction to Sealed Types .........................................................................................................................................285 Sealed Classes ......................................................................................................................................................................287 Why Is the sealed Modifier Required At All? .............................................................................................................288 Restrictions of a Sealed Type’s Subtype .....................................................................................................................290 Sealed Types vs Enum Classes .......................................................................................................................................291 Summary ...............................................................................................................................................................................294 Kotlin: An Illustrated Guideiv
Handling Runtime Exceptions Problems at Runtime .........................................................................................................................................................297 Catching Exceptions ..........................................................................................................................................................304 Throwing Exceptions ........................................................................................................................................................309 Exception Types ..................................................................................................................................................................310 Handling Multiple Exception Types Differently .......................................................................................................313 Evaluating a Try Expression ............................................................................................................................................315 Try-Catch-Finally .................................................................................................................................................................316 A Functional Approach to Exception Handling .......................................................................................................318 Summary ...............................................................................................................................................................................319 Generics Mugs and Beverages .........................................................................................................................................................323 Declared Types, Actual Types, and Assignment Compatibility ..........................................................................326 Introduction to Generic Types .......................................................................................................................................328 Type Parameter Constraints ...........................................................................................................................................330 Generics in Practice ...........................................................................................................................................................332 Generics in the Standard Library ..................................................................................................................................335 Trade-Offs of Generics ......................................................................................................................................................336 Summary ...............................................................................................................................................................................339 Generic Variance Covariance ............................................................................................................................................................................342 Contravariance ....................................................................................................................................................................348 What Makes a Subtype a Subtype? ..............................................................................................................................353 Variance Modifiers .............................................................................................................................................................354 Variance on Multiple Type Parameters .......................................................................................................................358 Type Projections .................................................................................................................................................................359 Variance in the Standard Library ..................................................................................................................................365 Summary ...............................................................................................................................................................................365 Coroutine Essentials One Thing at a Time… ......................................................................................................................................................368 Coroutines and Concurrency .........................................................................................................................................371 Two Things at a Time… ....................................................................................................................................................380 Two Robots, Two Things at a Time… ...........................................................................................................................386 Cancellations ........................................................................................................................................................................395 vTable of Contents
When We Can’t Recover From a Problem ..................................................................................................................402 Farewell, Rusty & Company! ...........................................................................................................................................404 Summary ...............................................................................................................................................................................404 Kotlin: An Illustrated Guidevi
viiPreface Thank you for purchasing this book! You’ve worked hard for your money, so I want this book to be everything that you hope it is. 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 rather than an uncertain, tenuous foundation of ambiguity. Even if you already know some of the concepts presented in this book, my goal is to give those concepts such a fun and vivid presentation that you’ll enjoy reading about them again, which I hope will give you a definite clarity about them, shining light on the foggy corners of concepts that you might have wondered about. What’s the current state of this book? This book is in active development. Currently, you’ll find the same main content as the online version of the book, plus you’ve got access to draft chapters as they’re written. • Chapters 1-19 are complete. You’re welcome to provide feedback about them. • Chapter 20, the final chapter of the book, is available in draft form for you to preview. • A few small appendices will be added, as well. My main focus at the moment is to complete the remaining chapters. After that, I’ll plan to return to earlier chapters in order to improve the quality of the images (improving resolution for PDF quality). Laying out this content in book format - that is, with a definite page size and hard page breaks - is quite different from laying out content on a web page. On the one hand, it’s easier because multiple screen sizes and resolutions don’t need to be accounted for. On the other hand, hard page breaks add a challenge of splitting the content at inconvenient points, such as in the middle of an illustration or code listing. In this version of the book, I’ve laid out the content to keep entire code listings on one page as much as possible, but you’ll find some extra white space as a result. Once the main content has been finalized, I intend to optimize the layout to make everything flow well and to minimize blank space. viiPreface Preface
Kotlin: An Illustrated Guideviii
Like all software developers, I have a tendency to underestimate how long a project can take. I expected to finish this book within a year or two while still working a full-time job. Here I am, about four years in, still working on it, and I’ve had lots of help and support along the way. First, I’m very thankful to my wife Elizabeth for all the evening and weekend hours that she gave up so that I could write this book. She’s been a massive support and encouragement to me at every step along the way. She’s always cheering me on! Thanks to Beverly, 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 I am today without her guidance and leadership. Thanks to these friends I’ve worked with, who have been especially encouraging as I’ve been writing about Kotlin - Beebe, Butler, Ensor, Fleckenstein, Jared, Majtan, McSorley, Pinzur, Rakidzich, and everyone else. Thanks so much to the following reviewers: I’m very grateful to both Kotlin Weekly and Android Weekly for all the times that they’ve included my articles, chapters, and videos in their weekly newsletters. Thanks to the Kotlin developer advocates at JetBrains - especially Hadi Hariri, who years ago suggested that I consider creating a Leanpub edition of this book! Thanks to the entire Kotlin community for your kind words of encouragement over the years. You’ve got no idea how much that’s meant to me! • James Lorenzen • David Blanc • Louis CAD • Matt McKenna • Mohit Sarveiya • Tobenna Ezike • Esraa Ibrahim • Charles Muchene • Raheel Naz • Jacob Rakidzich • Doug Smith • Jayant Varma • gbagd24 (…never did get your real name…!) ixAcknowledgments Acknowledgments
Variables, Expressions, and Types Kotlin: An Illustrated Guide Chapter 1
11 Kotlin: An Illustrated Guide Leave feedback 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 core 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! li : An Illustrated Guide
Introduction to Variables This is a circle. Thousands of years ago, a Greek fellow named Archimedes roughly figured out how to measure the length of the outside of a circle, called the circumference. You probably remember the equation the good old days of junior high school… “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 - a number that measures 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 itself; it’s just sort of a “bucket” that holds a number - any number. Variables aren’t just for algebra and geometry. They’re also used all the time in programming, where they serve the same purpose: holding values. In Kotlin, you can create a variable and put a number into it like this: Circumference = 2 r circumference r 12Leave feedback Chapter 1 • Variables, Expressions, and Types
This code is actually doing two things on one line. 1. Declaration - When we write var r, were declaring a new variable called r. You can think of declaring a variable as 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. var is just one of many keywords that we’ll see as we continue to learn Kotlin. The important thing to remember about keywords is that they can’t be used as the name of your own things. For example, you can’t use var as the name of the variable: var r = 5.2 assignment declaration Listing 1.1 - Creating a variable in Kotlin. var r = 5.2 var r = 5.2 variable name keyword value 13 Kotlin: An Illustrated Guide Leave feedback
We’ll come across other keywords in future chapters. Reassigning Variables As we noted above, in the equation 2πr, the variable r can represent different numbers in different situations. In Kotlin, if you decide that you want r to represent a different number, you can just reassign it, as shown in the second line here: When reassigning this variable, we didn’t need to use the var keyword again, because the variable was already declared on that first line. Variables that Cannot Be Reassigned Let’s look at that circumference equation again: The Greek letter π (pronounced like the word “pie”) is very different from the variable r. Whereas r can hold any number in it, π only ever holds one very specific number, which we’ll abbreviate to 3.14. In the same way, when programming in Kotlin, there are times when you want to make sure that a variable never changes. 10.05.2 6.7 Listing 1.3 - Assigning and then reassigning a value to a variable var r = 5.2 r = 6.7 Circumference = 2 r Listing 1.2 - Error: "Expecting property name or receiver type" (does not compile) var var = 5.2 14Leave feedback Chapter 1 • Variables, Expressions, and Types
In those cases, instead of declaring it with var, you declare it with val, like this: Now, if you try to reassign π, you’ll get an error: Once you put something in this bucket, you can never replace it! Declaring your variables with val is a great way to make sure that you don’t accidentally change something that shouldn’t change. In fact, it’s a great idea to always start with val, and only switch to var when you absolutely need to. For the Nerds If you’re already familiar with the concept of objects, it’s important to note that val does not make objects immutable. In other words, you can’t put something new in that bucket, but what’s in that bucket could still change itself in some way. That’s why Kotlin programmers tend to call variables declared with val “read-only” instead of “immutable”. We’ll cover this distinction in more detail once we get to the chapter on classes and objects. Naming Variables It’s been fun using the letter π in our code, but unless you live in Greece, you probably don’t have it on your keyboard. From here on out, we’ll make life easier for everyone by naming it pi instead. Also, instead of r, we’ll name it radius, so that any other developers who come along later will know exactly what that variable represents - we don’t want others to have to guess what the letter r stands for! Sometimes you need more than one word for a variable’s identifier. In Kotlin, it’s customary to start the first word in lowercase, and then capitalize the remaining words, like this: Listing 1.5 - Error: "Val cannot be reassigned" (does not compile). val π = 3.14 π = 1.23 Listing 1.4 - Creating a read-only variable in Kotlin val π = 3.14 15 Kotlin: An Illustrated Guide Leave feedback
Best Practice It’s a good idea to write your code in a way that’s similar to other developers, so that when everyone looks at it, they don’t have to think too hard about it. The official Kotlin documentation provides a set of coding conventions, and it’s recommended that you follow those. In case you use IntelliJ or Android Studio, that document also tells you how you can configure a formatter that will help you more easily conform to some of those conventions. Now that you’ve got down the basics for declaring and assigning variables, we can start assigning more than just simple numbers - we can start assigning more complex calculations, such as our circumference equation! Let’s dive into expressions! Expressions and Statements Let’s look at that equation one more time: We’ve already created a variable for pi and a variable for radius, so now we just need Kotlin to do some math for us, and we can get the circumference of any circle, regardless of how big that circle is. All we have to do is multiply together 2, pi, and radius. In Kotlin, as in most programming languages, multiplication isn’t represented with an x, it’s represented with an asterisk: *, so our code can look like this: So far we’ve only assigned simple values - such as 5.2 and 3.14. This is the first time we’re assigning something more complex: 2 * pi * radius. When Kotlin sees this, it simply calculates the result for you - it multiplies 2 times pi times radius, and then, of course, it takes the resulting value and assigns it to the variable named circumference. In this case (with a radius of 5.2), circumference will equal 32.656. Circumference = 2 r Listing 1.7 - Assigning a complex expression to a variable. var radius = 5.2 val pi = 3.14 val circumference = 2 * pi * radius Listing 1.6 -Variable naming convention in Kotlin: camel case. var radiusOfTheCircle = 5.2 16Leave feedback Chapter 1 • Variables, Expressions, and Types
Comments 0
Loading comments...
Reply to Comment
Edit Comment