Statistics
3
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-02

AuthorDmitry Jemerov, Svetlana Isakova

Kotlin in Action guides experienced Java developers from the language basics of Kotlin all the way through building applications to run on the JVM and Android devices.

Tags
No tags
ISBN: 1617293296
Publisher: Manning Publications
Publish Year: 2017
Language: 英文
Pages: 360
File Format: PDF
File Size: 10.3 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.

M A N N I N G Dmitry Jemerov Svetlana Isakova FOREWORD BY Andrey Breslav
Kotlin in Action
(This page has no text content)
Kotlin in Action DMITRY JEMEROV AND SVETLANA ISAKOVA M A N N I N G SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2017 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Dan Maharry 20 Baldwin Road Review editor: Aleksandar Dragosavljević PO Box 761 Technical development editor: Brent Watson Shelter Island, NY 11964 Project editor: Kevin Sullivan Copyeditor: Tiffany Taylor Proofreader: Elizabeth Martin Technical proofreader: Igor Wojda Typesetter: Marija Tudor Cover designer: Marija Tudor ISBN 9781617293290 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17
brief contents PART 1 INTRODUCING KOTLIN ................................................... 1 1 ■ Kotlin: what and why 3 2 ■ Kotlin basics 17 3 ■ Defining and calling functions 44 4 ■ Classes, objects, and interfaces 67 5 ■ Programming with lambdas 103 6 ■ The Kotlin type system 133 PART 2 EMBRACING KOTLIN ................................................... 171 7 ■ Operator overloading and other conventions 173 8 ■ Higher-order functions: lambdas as parameters and return values 200 9 ■ Generics 223 10 ■ Annotations and reflection 254 11 ■ DSL construction 282v
BRIEF CONTENTSvi
vii contents foreword xv preface xvii acknowledgments xix about this book xxi about the authors xxiv about the cover illustration xxv PART 1 INTRODUCING KOTLIN .................................... 1 1 Kotlin: what and why 3 1.1 A taste of Kotlin 3 1.2 Kotlin’s primary traits 4 Target platforms: server-side, Android, anywhere Java runs 4 Statically typed 5 ■ Functional and object-oriented 6 Free and open source 7 1.3 Kotlin applications 7 Kotlin on the server side 8 ■ Kotlin on Android 9 1.4 The philosophy of Kotlin 10 Pragmatic 10 ■ Concise 11 ■ Safe 12 ■ Interoperable 12 1.5 Using the Kotlin tools 13 Compiling Kotlin code 13 ■ Plug-in for IntelliJ IDEA and Android Studio 14 ■ Interactive shell 15 ■ Eclipse plug-in 15 Online playground 15 ■ Java-to-Kotlin converter 15 1.6 Summary 15
CONTENTSviii2 Kotlin basics 17 2.1 Basic elements: functions and variables 18 Hello, world! 18 ■ Functions 18 ■ Variables 20 Easier string formatting: string templates 22 2.2 Classes and properties 23 Properties 23 ■ Custom accessors 25 ■ Kotlin source code layout: directories and packages 26 2.3 Representing and handling choices: enums and “when” 28 Declaring enum classes 28 ■ Using “when” to deal with enum classes 29 ■ Using “when” with arbitrary objects 30 Using “when” without an argument 31 ■ Smart casts: combining type checks and casts 31 ■ Refactoring: replacing “if” with “when” 33 ■ Blocks as branches of “if” and “when” 34 2.4 Iterating over things: “while” and “for” loops 35 The “while” loop 35 ■ Iterating over numbers: ranges and progressions 36 ■ Iterating over maps 37 ■ Using “in” to check collection and range membership 38 2.5 Exceptions in Kotlin 39 “try”, “catch”, and “finally” 40 ■ “try” as an expression 41 2.6 Summary 42 3 Defining and calling functions 44 3.1 Creating collections in Kotlin 45 3.2 Making functions easier to call 46 Named arguments 47 ■ Default parameter values 48 Getting rid of static utility classes: top-level functions and properties 49 3.3 Adding methods to other people’s classes: extension functions and properties 51 Imports and extension functions 53 ■ Calling extension functions from Java 53 ■ Utility functions as extensions 54 No overriding for extension functions 55 ■ Extension properties 56 3.4 Working with collections: varargs, infix calls, and library support 57 Extending the Java Collections API 57 ■ Varargs: functions that accept an arbitrary number of arguments 58 ■ Working with pairs: infix calls and destructuring declarations 59
CONTENTS ix3.5 Working with strings and regular expressions 60 Splitting strings 60 ■ Regular expressions and triple-quoted strings 61 ■ Multiline triple-quoted strings 62 3.6 Making your code tidy: local functions and extensions 64 3.7 Summary 66 4 Classes, objects, and interfaces 67 4.1 Defining class hierarchies 68 Interfaces in Kotlin 68 ■ Open, final, and abstract modifiers: final by default 70 ■ Visibility modifiers: public by default 73 Inner and nested classes: nested by default 75 ■ Sealed classes: defining restricted class hierarchies 77 4.2 Declaring a class with nontrivial constructors or properties 78 Initializing classes: primary constructor and initializer blocks 79 Secondary constructors: initializing the superclass in different ways 81 ■ Implementing properties declared in interfaces 83 Accessing a backing field from a getter or setter 85 Changing accessor visibility 86 4.3 Compiler-generated methods: data classes and class delegation 87 Universal object methods 87 ■ Data classes: autogenerated implementations of universal methods 89 ■ Class delegation: using the “by” keyword 91 4.4 The “object” keyword: declaring a class and creating an instance, combined 93 Object declarations: singletons made easy 93 ■ Companion objects: a place for factory methods and static members 96 Companion objects as regular objects 98 ■ Object expressions: anonymous inner classes rephrased 100 4.5 Summary 101 5 Programming with lambdas 103 5.1 Lambda expressions and member references 104 Introduction to lambdas: blocks of code as function parameters 104 Lambdas and collections 105 ■ Syntax for lambda expressions 106 ■ Accessing variables in scope 109 Member references 111
CONTENTSx5.2 Functional APIs for collections 113 Essentials: filter and map 113 ■ “all”, “any”, “count”, and “find”: applying a predicate to a collection 115 groupBy: converting a list to a map of groups 117 flatMap and flatten: processing elements in nested collections 117 5.3 Lazy collection operations: sequences 118 Executing sequence operations: intermediate and terminal operations 120 ■ Creating sequences 122 5.4 Using Java functional interfaces 123 Passing a lambda as a parameter to a Java method 124 SAM constructors: explicit conversion of lambdas to functional interfaces 126 5.5 Lambdas with receivers: “with” and “apply” 128 The “with” function 128 ■ The “apply” function 130 5.6 Summary 131 6 The Kotlin type system 133 6.1 Nullability 133 Nullable types 134 ■ The meaning of types 136 ■ Safe call operator: “?.” 137 ■ Elvis operator: “?:” 139 ■ Safe casts: “as?” 140 ■ Not-null assertions: “!!” 141 ■ The “let” function 143 ■ Late-initialized properties 145 ■ Extensions for nullable types 146 ■ Nullability of type parameters 148 Nullability and Java 149 6.2 Primitive and other basic types 153 Primitive types: Int, Boolean, and more 153 ■ Nullable primitive types: Int?, Boolean?, and more 154 ■ Number conversions 155 “Any” and “Any?”: the root types 157 ■ The Unit type: Kotlin’s “void” 157 ■ The Nothing type: “This function never returns” 158 6.3 Collections and arrays 159 Nullability and collections 159 ■ Read-only and mutable collections 161 ■ Kotlin collections and Java 163 Collections as platform types 165 ■ Arrays of objects and primitive types 167 6.4 Summary 170
CONTENTS xi PART 2 EMBRACING KOTLIN .................................... 171 7 Operator overloading and other conventions 173 7.1 Overloading arithmetic operators 174 Overloading binary arithmetic operations 174 ■ Overloading compound assignment operators 177 ■ Overloading unary operators 178 7.2 Overloading comparison operators 180 Equality operators: “equals” 180 ■ Ordering operators: compareTo 181 7.3 Conventions used for collections and ranges 182 Accessing elements by index: “get” and “set” 182 ■ The “in” convention 184 ■ The rangeTo convention 185 ■ The “iterator” convention for the “for” loop 186 7.4 Destructuring declarations and component functions 187 Destructuring declarations and loops 188 7.5 Reusing property accessor logic: delegated properties 189 Delegated properties: the basics 189 ■ Using delegated properties: lazy initialization and “by lazy()” 190 ■ Implementing delegated properties 192 ■ Delegated-property translation rules 195 Storing property values in a map 196 ■ Delegated properties in frameworks 197 7.6 Summary 199 8 Higher-order functions: lambdas as parameters and return values 200 8.1 Declaring higher-order functions 201 Function types 201 ■ Calling functions passed as arguments 202 ■ Using function types from Java 204 Default and null values for parameters with function types 205 Returning functions from functions 207 ■ Removing duplication through lambdas 209 8.2 Inline functions: removing the overhead of lambdas 211 How inlining works 211 ■ Restrictions on inline functions 213 Inlining collection operations 214 ■ Deciding when to declare functions as inline 215 ■ Using inlined lambdas for resource management 216
CONTENTSxii8.3 Control flow in higher-order functions 217 Return statements in lambdas: return from an enclosing function 217 ■ Returning from lambdas: return with a label 218 ■ Anonymous functions: local returns by default 220 8.4 Summary 221 9 Generics 223 9.1 Generic type parameters 224 Generic functions and properties 224 ■ Declaring generic classes 226 ■ Type parameter constraints 227 Making type parameters non-null 229 9.2 Generics at runtime: erased and reified type parameters 230 Generics at runtime: type checks and casts 230 ■ Declaring functions with reified type parameters 233 ■ Replacing class references with reified type parameters 235 ■ Restrictions on reified type parameters 236 9.3 Variance: generics and subtyping 237 Why variance exists: passing an argument to a function 237 Classes, types, and subtypes 238 ■ Covariance: preserved subtyping relation 240 ■ Contravariance: reversed subtyping relation 244 ■ Use-site variance: specifying variance for type occurrences 246 ■ Star projection: using * instead of a type argument 248 9.4 Summary 252 10 Annotations and reflection 254 10.1 Declaring and applying annotations 255 Applying annotations 255 ■ Annotation targets 256 Using annotations to customize JSON serialization 258 Declaring annotations 260 ■ Meta-annotations: controlling how an annotation is processed 261 ■ Classes as annotation parameters 262 ■ Generic classes as annotation parameters 263 10.2 Reflection: introspecting Kotlin objects at runtime 264 The Kotlin reflection API: KClass, KCallable, KFunction, and KProperty 265 ■ Implementing object serialization using reflection 268 ■ Customizing serialization with annotations 270 JSON parsing and object deserialization 273 ■ Final deserialization step: callBy() and creating objects using reflection 277 10.3 Summary 281
CONTENTS xiii11 DSL construction 282 11.1 From APIs to DSLs 283 The concept of domain-specific languages 284 ■ Internal DSLs 285 ■ Structure of DSLs 286 ■ Building HTML with an internal DSL 287 11.2 Building structured APIs: lambdas with receivers in DSLs 288 Lambdas with receivers and extension function types 288 Using lambdas with receivers in HTML builders 292 Kotlin builders: enabling abstraction and reuse 296 11.3 More flexible block nesting with the “invoke” convention 299 The “invoke” convention: objects callable as functions 299 The “invoke” convention and functional types 300 ■ The “invoke” convention in DSLs: declaring dependencies in Gradle 301 11.4 Kotlin DSLs in practice 303 Chaining infix calls: “should” in test frameworks 303 ■ Defining extensions on primitive types: handling dates 305 ■ Member extension functions: internal DSL for SQL 306 ■ Anko: creating Android UIs dynamically 309 11.5 Summary 310 appendix A Building Kotlin projects 313 appendix B Documenting Kotlin code 317 appendix C The Kotlin ecosystem 320 index 323
CONTENTSxiv
foreword When I visited JetBrains for the first time in Spring 2010, I came in fairly certain that the world didn’t need another general-purpose programming language. I thought that existing JVM languages were good enough, and who in their right mind creates a new language anyway? After about an hour discussing production issues in large-scale codebases I was convinced otherwise, and the first ideas that later became part of Kot- lin were sketched on a whiteboard. I joined JetBrains shortly after to lead the design of the language and work on the compiler. Today, more than six years later, we have our second release approaching. There are over 30 people on the team and thousands of active users, and we still have more exciting design ideas than I can handle easily. But don't worry, those ideas have to pass a rather thorough examination before they get into the language. We want Kotlin of the future to still fit into a single reasonably sized book. Learning a programming language is an exciting and often very rewarding endeavor. If it’s your first one, you’re learning the whole new world of programming through it. If it’s not, it makes you think about familiar things in new terms and thus understand them more deeply and on a higher level of abstraction. This book is pri- marily targeted for the latter kind of reader, those already familiar with Java. Designing a language from scratch may be a challenging task in its own right, but making it play well with another is a different story—one with many angry ogres in it, and some gloomy dungeons too. (Ask Bjarne Stroustrup, the creator of C++, if you don’t trust me on that.) Java interoperability (that is, how Java and Kotlin can mix and call each other) was one of the cornerstones of Kotlin, and this book pays a lot of atten- tion to it. Interoperability is very important for introducing Kotlin gradually to an exist- ing Java codebase. Even when writing a new project from scratch, one has to fit the language into the bigger picture of the platform with all of its libraries written in Java.xv
FOREWORDxvi As I’m writing this, two new target platforms are being developed: Kotlin is now running on JavaScript VMs enabling full-stack web development, and it will soon be able to compile directly to native code and run without any VM at all, if necessary. So, while this book is JVM-oriented, much of what you learn from it can be applied to other execution environments. The authors have been members of the Kotlin team from its early days, so they are intimately familiar with the language and its internals. Their experience in confer- ence presentations, workshops, and courses about Kotlin has enabled them to deliver good explanations that anticipate common questions and possible pitfalls. The book explains high-level concepts behind language features and provides all the necessary details as well. I hope you’ll enjoy your time with our language and this book. As I often say in our community postings: Have a nice Kotlin! ANDREY BRESLAV LEAD DESIGNER OF KOTLIN AT JETBRAINS
preface The idea of Kotlin was conceived at JetBrains in 2010. By that time, JetBrains was an established vendor of development tools for many languages, including Java, C#, JavaScript, Python, Ruby, and PHP. IntelliJ IDEA, the Java IDE that is our flagship prod- uct, also included plugins for Groovy and Scala. The experience of building the tooling for such a diverse set of languages gave us a unique understanding of and perspective on the language design space as a whole. And yet the IntelliJ Platform-based IDEs, including IntelliJ IDEA, were still being devel- oped in Java. We were somewhat envious of our colleagues on the .NET team who were developing in C#, a modern, powerful, rapidly evolving language. But we didn’t see any language that we could use instead of Java. What were our requirements for such a language? The first and most obvious was static typing. We don’t know any other way to develop a multimillion-line codebase over many years without going crazy. Second, we needed full compatibility with the existing Java code. That codebase is a hugely valuable asset for JetBrains, and we couldn’t afford to lose it or devalue it through difficulties with interoperability. Third, we didn’t want to accept any compromises in terms of tooling quality. Developer pro- ductivity is the most important value for JetBrains as a company, and great tooling is essential to achieving that. Finally we needed a language that was easy to learn and to reason about. When we see an unmet need for our company, we know there are other companies in similar situations, and we expect that our solution will find many users outside of Jet- Brains. With this in mind, we decided to embark on the project of creating a new lan- guage: Kotlin. As it happens, the project took longer than we expected, and Kotlin 1.0xvii
PREFACExviiicame out more than five years after the first commit to the repository; but now we can be certain that the language has found its audience and is here to stay. Kotlin is named after an island near St. Petersburg, Russia, where most of the Kot- lin development team is located. In using an island name, we followed the precedent established by Java and Ceylon, but we decided to go for something closer to our homes. (In English, the name is usually pronounced “cot-lin,” not “coat-lin” or “caught-lin.”) As the language was approaching release, we realized that it would be valuable to have a book about Kotlin, written by people who were involved in making design deci- sions for the language and who could confidently explain why things in Kotlin are the way they are. This book is a result of that effort, and we hope it will help you learn and understand the Kotlin language. Good luck, and may you always develop with pleasure!
acknowledgments First of all, we’d like to thank Sergey Dmitriev and Max Shafirov for believing in the idea of a new language and deciding to invest JetBrains’ resources. Without them, nei- ther the language nor this book would exist. We would especially like to acknowledge Andrey Breslav, who is the main person to blame for designing a language that’s a pleasure to write about (and to code in). Andrey, despite having to lead the continuously growing Kotlin team, was able to give us a lot of helpful feedback, which we greatly appreciate. In addition, you can be assured that this book received a stamp of approval from the lead language designer, in the form of the foreword that he kindly agreed to write. We’re grateful to the team at Manning who guided us through the process of writing this book and helped make the text readable and well-structured—particularly our development editor, Dan Maharry, who bravely strove to find time to talk despite our busy schedules, as well as Michael Stephens, Helen Stergius, Kevin Sullivan, Tiffany Tay- lor, Elizabeth Martin, and Marija Tudor. The feedback from our technical reviewers, Brent Watson and Igor Wojda, was also invaluable, as were the comments of the review- ers who read the manuscript during the development process: Alessandro Campeis, Amit Lamba, Angelo Costa, Boris Vasile, Brendan Grainger, Calvin Fernandes, Christo- pher Bailey, Christopher Bortz, Conor Redmond, Dylan Scott, Filip Pravica, Jason Lee, Justin Lee, Kevin Orr, Nicolas Frankel, Paweł Gajda, Ronald Tischliar, and Tim Lavers. Thanks go also to everyone who submitted feedback during the MEAP program and in the book’s forum; we’ve improved the text based on your comments. We’re grateful to the entire Kotlin team, who had to listen to daily reports like “One more section is finished!” throughout the time we spent writing this book. We want to thank our colleagues who helped us plan the book and gave feedback on itsxix