(This page has no text content)
Kotlin Cookbook A Problem-Focused Approach Ken Kousen
Kotlin Cookbook by Ken Kousen Copyright © 2020 Ken Kousen. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editors: Zan McQuade and Tyler Ortman Development Editor: Corbin Collins Production Editor: Christopher Faucher Copyeditor: Sharon Wilkey Proofreader: Charles Roumeliotis Indexer: Ellen Troutman-Zaig Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest November 2019: First Edition Revision History for the First Edition 2019-11-14: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492046677 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Kotlin Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-04667-7 [LSI]
Dedication For Sandra, who got me through this. Your kindness, unflagging support, and expert skills continue to change my life.
Foreword Every few years, there is a revolutionary new language that threatens to change the way that people write software. The reality seldom lives up to the hype. Kotlin is different. Since its creation back in 2011, it has slowly, almost imperceptibly, crept its way into codebases across the world. Developers who have used Java for so long and found it lacking have been able to sneak in a little Kotlin here and there. In so doing, they have shrunk the size—and increased the power—of their code. Having gained some fame as the preferred language for Android development, Kotlin is now at a sufficiently mature stage that a book like this is desperately needed. With a wealth of useful tips, Kotlin Cookbook begins at the beginning. Ken shows you how to install Kotlin and configure it for your project. He shows how to run it in a Java environment, in a browser, or as a standalone application. But the book quickly moves on, solving the kind of day-to-day programming problems faced by developers and architects everywhere. Although there is a section set aside for Kotlin testing, you will find that the book is itself test-driven. It uses tests as practical examples of how to use the language. The tests will allow you to adapt the recipes to fit your needs more precisely. This book brings you the kind of straightforward, practical help that will guide your progress on your Kotlin journey. It’s the essential how-to Kotlin guide, and every developer should keep it on their desktop (real or virtual) to support their daily work. Dawn and David Griffiths Authors, Head First Kotlin October 6, 2019
Preface Welcome to Kotlin Cookbook! The overall focus of the book is not only to teach Kotlin syntax and semantics, but also to show you when and why a particular feature should be used. The goal isn’t necessarily to cover every detail of Kotlin’s syntax and libraries. In the end, however, many recipes on basic principles were added to make the book understandable even to readers with only a beginning level of Kotlin knowledge. There is a strong movement by JetBrains to encourage the Kotlin community to embrace multiplatform, native, and JavaScript development. In the end, the decision was made not to include recipes involving them, since all are either in beta form or have very low adoption rates. As a result, the book concentrates exclusively on Kotlin for the JVM. The GitHub repository for all the code can be found at https://github.com/kousen/kotlin-cookbook. It includes a Gradle wrapper (with the build file written in the Kotlin DSL, of course) and all the tests pass. All of the code examples in the book have been compiled and tested with both available Long Term Support versions of Java, namely Java 8 and Java 11. Even though Java 8 is technically past its end-of-life deadline, it is still pervasive enough in the industry to ensure the code examples work with it. At the time of this writing, the current version of Kotlin is 1.3.50, with 1.3.60 on the way. All the code works with both versions, and the GitHub repository will frequently be updated to use the latest version of Kotlin. Who Should Read This Book This book is written for developers who already know the basics of object- oriented programming, especially in Java or another JVM-based language. While Java knowledge would be helpful, it isn’t required.
A recipe book like this one is more focused on using the techniques and idioms of Kotlin than on being an exhaustive resource on the language. That has the advantage of using the full power of the language in any given recipe, but the disadvantage of spending only a limited time on the basics of those features. Each chapter includes a summary of the basic techniques, so if you are only vaguely familiar with how to create collections, work with arrays, or design classes, you should still be fine. The online reference manual provides a solid introduction to the language, and the book makes frequent reference to examples and discussions found there. In addition, the book frequently dives into the implementations of features from the Kotlin libraries. That’s to show how the developers of the language work with it in practice, as well as to discuss why things are done the way they are. No prior knowledge of the implementation is expected, however, and you are free to skip those details if you are in a hurry.
How This Book Is Organized This book is organized into recipes, and while each is self-contained, many reference others in the book. The hope is that you can read them in any particular order. That said, there is a loose ordering to the chapters, as follows: Chapter 1 covers the basic process of installing and running Kotlin, including using the REPL, working with build tools like Maven and Gradle, and employing the native image generator in Graal. Chapter 2 covers some fundamental features of Kotlin—such as nullable types, overloading operators, and converting between types—before examining some more esoteric issues including working with bitwise shift operators or the to extension function on the Pair class. Chapter 3 focuses on object-oriented features of the language that developers from other languages might find surprising or unusual. It includes how to use the const keyword, how Kotlin handles backing properties, delayed initialization, and the dreaded Nothing class, which is guaranteed to confuse existing Java developers. Chapter 4 has only a few recipes, which involve functional features that need their own explanations. Functional programming concepts are covered throughout the book, especially when talking about collections, sequences, and coroutines, but there are a handful of techniques included in this chapter that you may find unusual or particularly interesting. Chapter 5 covers arrays and collections, dealing mostly with nonobvious methods like destructing collections, sorting by multiple properties, building a window on a collection, and creating progressions. Chapter 6 shows how Kotlin handles sequences of items lazily, similar to the way Java uses streams. Recipes cover generating sequences, yielding from them, and working with infinite sequences. Chapter 7 covers another topic unique to Kotlin: functions that execute a block of code in the context of an object. Functions like let, apply, and
also are quite useful in Kotlin, and this chapter illustrates why and how to use them. Chapter 8 discusses a convenient feature of Kotlin: how it implements delegation. Delegation lets you employ composition rather than inheritance, and Kotlin includes several delegates in the standard library, like lazy, observable, and vetoable. Chapter 9 covers the important topic of testing, with a particular focus on JUnit 5. In its current version, JUnit is designed to work well with Kotlin, and that includes both its regular usage and employing it in Spring Framework applications. This chapter discusses several approaches that make writing and executing tests easier. Chapter 10 includes a couple of recipes specifically for managing resources. File I/O is covered, as is the use function, which has broad applicability in several contexts. Chapter 11 covers topics that do not fit easily in any other category. Topics such as how to get the current Kotlin version, how to force the when statement to be exhaustive even when it doesn’t return a value, and how to use the replace function with regular expressions are covered. In addition, the TODO function and the Random class are discussed, as well as how to integrate with Java exception handling. Chapter 12 involves the Spring Framework along with Spring Boot, which is very friendly to Kotlin. A few recipes are included to show how to use Kotlin classes as managed beans, how to implement JPA persistence, and how to inject dependencies when needed. Chapter 13 covers the subject of coroutines, one of the most popular features of Kotlin and the basis of concurrent and parallel programming in the language. Recipes cover the basics, like builders and dispatchers, along with how to cancel and debug coroutines, and how to run them on your own custom Java thread pool. The chapters, and indeed the recipes themselves, do not have to be read in any particular order. They do complement each other, and each recipe ends
with references to others, but you can start reading anywhere. The chapter groupings are provided as a way to put similar recipes together, but it is expected that you will jump from one to another to solve whatever problem you may have at the moment. Special note for Android developers: Kotlin is now the preferred language for Android development, but it is a much broader, general-purpose programming language. You can use it anywhere you would use Java, and more. This book does not have a dedicated section just for Android. Instead, Android uses of Kotlin are discussed throughout. A few specific Android- related recipes, like coroutine cancellation, take advantage of the fact that Android libraries make extensive use of Kotlin, but in general the features of the language covered in this book can be used anywhere. It is hoped that by covering the language in a more general way, Android developers will find techniques useful to them in any coding project. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context.
TIP This element signifies a tip or suggestion. NOTE This element signifies a general note. WARNING This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/kousen/kotlin-cookbook. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not generally require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Kotlin Cookbook by Ken Kousen (O’Reilly). Copyright 2020 Ken Kousen, 978-1- 492-04667-7.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, conferences, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, please visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information: https://oreil.ly/kotlin-cookbook. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments At the Google I/O conference in 2017, the company announced that Kotlin would be a supported language for Android development. Later that year, Gradle, Inc.—the company behind the Gradle build tool—announced that it would support a Gradle domain-specific language (DSL) for builds. Both of those developments convinced me to dig into the language, and I’ve been happy to have done so. Over the past few years, I’ve been giving regular presentations and workshops on Kotlin. While the basics of the language are easy to learn and apply, I’ve been impressed with its depth and how aware it is of the way modern development ideas are implemented in other languages, like Groovy or Scala. Kotlin is a synthesis of many of the best programming ideas throughout the industry, and I’ve learned a lot by doing the deep dive necessary to write a book like this. As part of my learning process, I’ve benefitted from working with many active Kotlin developers, including Dawn and Dave Griffiths, whose books Head First Android Development and Head First Kotlin are outstanding; they even agreed to write the foreword for this book. Hadi Harriri, a developer advocate at JetBrains, gives presentations on Kotlin on a regular basis. Those talks always inspire me to spend time on the language, and he was kind enough to be a technical reviewer for this book. I’m very grateful to them. Bill Fly also provided a technical review. I’ve interacted with him on the O’Reilly Learning Platform more times than I can count, and he always provides interesting insights (and hard questions). My good friend Jim
Harmon helped me get up to speed on Android many years ago, and has always been willing to answer my questions and talk about how Kotlin is used in practice. Mark Maynard is an active developer in industry who helped me understand how Kotlin worked with the Spring Framework, and I’m grateful for that. Finally, the inimitable Venkat Subramaniam was kind enough to take time from his busy schedule writing his own Kotlin book (entitled Programming Kotlin: it’s as good as the rest of his books) to help me with mine. I’m happy to know all my tech reviewers and am humbled by the amount of time and effort they spent improving the book you see now. I need to acknowledge many of my fellow speakers on the NFJS tour, including Nate Schutta, Michael Carducci, Matt Stine, Brian Sletten, Mark Richards, Pratik Patel, Neal Ford, Craig Walls, Raju Gandhi, Jonathan Johnson, and Dan “the Man” Hinojosa for their constant doses of perspective and encouragement. I’m sure I’ve left out someone on the tour, and, if so, I assure you it was deliberate. Okay, maybe not. Writing books and teaching training classes (my actual day job) are solitary pursuits. It’s great having a community of friends and colleagues that I can rely on for perspective, advice, and various forms of entertainment. Many people at O’Reilly Media were involved in the creation of this book. Rather than call them out individually, I specifically want to mention Zan McQuade, who was frequently placed in awkward positions by my irregular schedule and my general contrary nature. Thank you for your patience, understanding, and hard work to bring the book to completion. Finally, I need to express all my love to my wife, Ginger, and my son, Xander. Without the support and kindness of my family, I would not be the person I am today, a fact that grows more obvious to me with each passing year. I can never express what you both mean to me.
Chapter 1. Installing and Running Kotlin The recipes in this chapter help you get up and running with the Kotlin compiler, both from the command line and using an integrated development environment (IDE). 1.1 Running Kotlin Without a Local Compiler Problem You want to try out Kotlin without a local installation, or run it on a machine that does not support it (for example, a Chromebook). Solution Use the Kotlin Playground, an online sandbox for exploring Kotlin. Discussion The Kotlin Playground provides an easy way to experiment with Kotlin, explore features you haven’t used, or simply run Kotlin on systems that don’t have an installed compiler. It gives you access to the latest version of the compiler, along with a web-based editor that allows you to add code without installing Kotlin locally. Figure 1-1 is a snapshot of the browser page.
Figure 1-1. The Kotlin Playground home page Just type in your own code and click the Play button to execute it. The Settings button (the gear icon) allows you to change Kotlin versions, decide which platform to run on (JVM, JS, Canvas, or JUnit), or add program arguments. NOTE As of Kotlin 1.3, the Kotlin function main can be defined without parameters. The Examples section contains an extensive set of sample programs, organized by topic, that can be executed using an embedded block in a browser. Figure 1-2 shows the “Hello world” program page.
Figure 1-2. Examples in the Kotlin Playground The playground also has a dedicated section for Kotlin Koans, which are a series of exercises to help you become more familiar with the language. While these are useful online, if you use IntelliJ IDEA or Android Studio, the Koans can be added using the EduTools plug-in. 1.2 Installing Kotlin Locally Problem You want to execute Kotlin from a command prompt on your local machine. Solution
Perform a manual install from GitHub or use one of the available package managers for your operating system. Discussion The page at http://kotlinlang.org/docs/tutorials/command-line.html discusses the options for installing a command-line compiler. One option is to download a ZIP file containing an installer for your operating system. This page contains a link to the GitHub repository for Kotlin current releases. ZIP files are available for Linux, macOS, Windows, and the source distribution. Simply unzip the distribution and add its bin subdirectory to your path. A manual install certainly works, but some developers prefer to use package managers. A package manager automates the installation process, and some of them allow you to maintain multiple versions of a particular compiler. SDKMAN!, Scoop, and other package managers One of the most popular installation programs is SDKMAN!. Originally designed for Unix-based shells, there are plans to make it available for other platforms as well. Installing Kotlin with SDKMAN! begins with a curl install: > curl -s https://get.sdkman.io | bash Then, once it’s installed, you can use the sdk command to install any one of a variety of products, including Kotlin: > sdk install kotlin By default, the latest version will be installed in the ~/.sdkman/candidates/kotlin directory, along with a link called current that points to the selected version. You can find out what versions are available by using the list command:
> sdk list kotlin The install command by default selects the latest version, but the use command will let you select any version, offering to install it if necessary: > sdk use kotlin 1.3.50 That will install version 1.3.50 of Kotlin, if necessary, and use it in the current shell. NOTE IntelliJ IDEA or Android Studio can use the downloaded versions, or they can maintain their own versions separately. Other package managers that support Kotlin include Homebrew, MacPorts, and Snapcraft. On Windows, you can use Scoop. Scoop does for Windows what the other package managers do for non-Windows systems. Scoop requires PowerShell 5 or later and .NET Framework 4.5 or later. Simple installation instructions are found on the Scoop website. Once Scoop is installed, the main bucket allows you to install the current version of Kotlin: > scoop install kotlin This will install the scripts kotlin.bat, kotlinc.bat, kotlin-js.bat, and kotlin- jvm.bat and add them all to your path. That is sufficient, but if you want to try it, there is an experimental installer called kotlin-native, which installs a native Windows compiler as well. This installs an LLVM backend for the Kotlin compiler, a runtime implementation, and a native code generation facility by using the LLVM toolchain.
Comments 0
Loading comments...
Reply to Comment
Edit Comment