28,99 €
Learn to program with Kotlin, one of the fastest-growing programming languages available today Programming Kotlin Applications: Building Mobile and Server-Side Applications with Kotlin drops readers into the fast lane for learning to develop with the Kotlin programming language. Authored by accomplished cloud consultant and technology professional Brett McLaughlin, Programming Kotlin Applications provides readers with the pragmatic and practical advice they need to build their very first Kotlin applications. Designed to give readers a thorough understanding of Kotlin that goes beyond mere mobile programming, this book will help you: * Learn how to develop your first Kotlin project * Understand how Kotlin securely protects and stores information * Advocate for using Kotlin in your own professional and personal environments * Understand Kotlin's goals and how to use it as its best * Know when to avoid using Kotlin Programming Kotlin Applications is written in a highly approachable and accessible way without the fluff and unrealistic samples that characterize some of its competitor guides. Perfect for developers familiar with another object-oriented programming language like Java or Ruby, or for people who want to advance their skillset in the Kotlin environment, this book is an indispensable addition to any programmer's library.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 546
Veröffentlichungsjahr: 2020
COVER
TITLE PAGE
COPYRIGHT
DEDICATION
ABOUT THE AUTHOR
ABOUT THE TECHNICAL EDITOR
ACKNOWLEDGMENTS
INTRODUCTION
WHAT DOES THIS BOOK COVER?
1 Objects All the Way Down
KOTLIN: A NEW PROGRAMMING LANGUAGE
WHAT IS KOTLIN?
KOTLIN IS OBJECT-ORIENTED
INTERLUDE: SET UP YOUR KOTLIN ENVIRONMENT
CREATING USEFUL OBJECTS
INITIALIZE AN OBJECT AND CHANGE A VARIABLE
2 It's Hard to Break Kotlin
UPGRADE YOUR KOTLIN CLASS GAME
KOTLIN HAS A LARGE NUMBER OF TYPES
OVERRIDING PROPERTY ACCESSORS AND MUTATORS
CLASSES CAN HAVE CUSTOM BEHAVIOR
TYPE SAFETY CHANGES EVERYTHING
WRITING CODE IS RARELY LINEAR
3 Kotlin Is Extremely Classy
OBJECTS, CLASSES, AND KOTLIN
ALL CLASSES NEED AN EQUALS(X) METHOD
EVERY OBJECT INSTANCE NEEDS A UNIQUE HASHCODE()
SEARCHING (AND OTHER THINGS) DEPEND ON USEFUL AND FAST EQUALS(X) AND HASHCODE()
BASIC CLASS METHODS ARE REALLY IMPORTANT
4 Inheritance Matters
GOOD CLASSES ARE NOT ALWAYS COMPLEX CLASSES
CLASSES CAN DEFINE DEFAULT VALUES FOR PROPERTIES
SECONDARY CONSTRUCTORS PROVIDE ADDITIONAL CONSTRUCTION OPTIONS
HANDLE DEPENDENT VALUES WITH CUSTOM MUTATORS
NEED SPECIFICS? CONSIDER A SUBCLASS
YOUR SUBCLASS SHOULD BE DIFFERENT THAN YOUR SUPERCLASS
5 Lists and Sets and Maps, Oh My!
LISTS ARE JUST A COLLECTION OF THINGS
LISTS (AND COLLECTIONS) CAN BE TYPED
LISTS ARE ORDERED AND CAN REPEAT
SETS: UNORDERED BUT UNIQUE
MAPS: WHEN A SINGLE VALUE ISN'T ENOUGH
FILTER A COLLECTION BY … ANYTHING
COLLECTIONS: FOR PRIMITIVE AND CUSTOM TYPES
6 The Future (in Kotlin) Is Generic
GENERICS ALLOW DEFERRING OF A TYPE
GENERICS TRY TO INFER A TYPE WHEN POSSIBLE
COVARIANCE: A STUDY IN TYPES AND ASSIGNMENT
CONTRAVARIANCE: BUILDING CONSUMERS FROM GENERIC TYPES
UNSAFEVARIANCE: LEARNING THE RULES, THEN BREAKING THEM
TYPEPROJECTION LETS YOU DEAL WITH BASE CLASSES
7 Flying through Control Structures
CONTROL STRUCTURES ARE THE BREAD AND BUTTER OF PROGRAMMING
IF AND ELSE: THE GREAT DECISION POINT
WHEN IS KOTLIN'S VERSION OF SWITCH
FOR IS FOR LOOPING
USE WHILE TO EXECUTE UNTIL A CONDITION IS FALSE
DO … WHILE ALWAYS RUNS ONCE
GET OUT OF A LOOP IMMEDIATELY WITH BREAK
GO TO THE NEXT ITERATION IMMEDIATELY WITH CONTINUE
RETURN RETURNS
8 Data Classes
CLASSES IN THE REAL WORLD ARE VARIED BUT WELL EXPLORED
A DATA CLASS TAKES THE WORK OUT OF A CLASS FOCUSED ON DATA
DESTRUCTURING DATA THROUGH DECLARATIONS
YOU CAN “COPY” AN OBJECT OR MAKE A COPY OF AN OBJECT
DATA CLASSES REQUIRE SEVERAL THINGS FROM YOU
DATA CLASSES ADD SPECIAL BEHAVIOR TO GENERATED CODE
DATA CLASSES ARE BEST LEFT ALONE
9 Enums and Sealed, More Specialty Classes
STRINGS ARE TERRIBLE AS STATIC TYPE REPRESENTATIONS
COMPANION OBJECTS ARE SINGLE INSTANCE
ENUMS DEFINE CONSTANTS AND PROVIDE TYPE SAFETY
SEALED CLASSES ARE TYPE-SAFE CLASS HIERARCHIES
10 Functions and Functions and Functions
REVISITING THE SYNTAX OF A FUNCTION
FUNCTIONS FOLLOW FLEXIBLE RULES
FUNCTIONS IN KOTLIN HAVE SCOPE
FUNCTION LITERALS: LAMBDAS AND ANONYMOUS FUNCTIONS
LOTS OF FUNCTIONS, LOTS OF ROOM FOR PROBLEMS
11 Speaking Idiomatic Kotlin
SCOPE FUNCTIONS PROVIDE CONTEXT TO CODE
USE LET TO PROVIDE IMMEDIATE ACCESS TO AN INSTANCE
WITH IS A SCOPE FUNCTION FOR PROCESSING AN INSTANCE
RUN IS A CODE RUNNER AND SCOPE FUNCTION
APPLY HAS A CONTEXT OBJECT BUT NO RETURN VALUE
ALSO GIVES YOU AN INSTANCE … BUT OPERATES ON THE INSTANCE FIRST
SCOPE FUNCTIONS SUMMARY
12 Inheritance, One More Time, with Feeling
ABSTRACT CLASSES REQUIRE A LATER IMPLEMENTATION
INTERFACES DEFINE BEHAVIOR BUT HAVE NO BODY
DELEGATION OFFERS ANOTHER OPTION FOR EXTENDING BEHAVIOR
INHERITANCE REQUIRES FORETHOUGHT AND AFTERTHOUGHT
13 Kotlin: The Next Step
PROGRAMMING KOTLIN FOR ANDROID
KOTLIN AND JAVA ARE GREAT COMPANIONS
WHEN KOTLIN QUESTIONS STILL EXIST
NOW WHAT?
INDEX
END USER LICENSE AGREEMENT
Chapter 2
TABLE 2.1: Kotlin Types for Integers (Nondecimal Numbers)
TABLE 2.2: Kotlin Types for Decimal Numbers
Chapter 6
TABLE 6.1: Differences between Covariant and Contravariant
Chapter 11
TABLE 11.1: Differences between scope functions
Chapter 1
FIGURE 1.1 Download IntelliJ from the JetBrains download page.
FIGURE 1.2 IntelliJ comes prepackaged with a system-specific installation pr...
FIGURE 1.3 You'll generally be either creating a project from scratch or imp...
FIGURE 1.4 IntelliJ makes getting going in Kotlin simple and prompts you on ...
FIGURE 1.5 Kotlin code should go in the src/ folder.
FIGURE 1.6 IntelliJ automatically formats code and adds sensible syntax high...
FIGURE 1.7 You can click the green Run button and select the first option to...
FIGURE 1.8 The empty output of your program (which will soon be non-empty) d...
FIGURE 1.9 Good IDEs help you quickly find and fix errors.
FIGURE 1.10 Why doesn't this override of toString() work?
Chapter 2
FIGURE 2.1 Your IDE should let you easily get to your source code as well as...
FIGURE 2.2 Moving a class to a new package is basically a refactoring, which...
FIGURE 2.3 Person is now nested under its containing package.
FIGURE 2.4 IDEs will help you keep constructor properties straight.
Chapter 4
FIGURE 4.1 Code from Person expanded completely
FIGURE 4.2 You can collapse code blocks to the { … } form in your IDE
FIGURE 4.3 Toggle between expanded and collapsed with the + and – icons
Chapter 5
FIGURE 5.1
Collection
and several related classes
Chapter 7
FIGURE 7.1 An if statement adjusts how your code is executed and the flow of...
FIGURE 7.2 Program execution has two different flows in this example.
Chapter 10
FIGURE 10.1 A function always has the same basic parts.
FIGURE 10.2 A good IDE gives you default values for a function, even from a ...
FIGURE 10.3 IDEs help with arguments, especially if you're naming arguments ...
FIGURE 10.4 An unused anonymous function
FIGURE 10.5 A function assigned to a variable is treated like the function i...
Chapter 11
FIGURE 11.1 Good IDEs warn you of conflicts in scope function variables.
FIGURE 11.2 Distinguishing between a String and a String?
FIGURE 11.3 An IDE helping with the this reference in a with expression
FIGURE 11.4 Kotlin suggests using run to both initialize an instance and get...
FIGURE 11.5 The also function provides an it reference to the context object...
Chapter 12
FIGURE 12.1 An inheritance hierarchy using interfaces, abstract classes, and...
FIGURE 12.2 The go() function in Vehicle eventually is handled by drive() im...
Chapter 13
FIGURE 13.1 Kotlin's reference documentation is thorough and helpful.
FIGURE 13.2 The Kotlin Koans aren't for everyone, but they're great for inte...
Cover Page
Table of Contents
Begin Reading
v
vi
vii
ix
xi
xiii
xxv
xxvi
xxvii
xxviii
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
339
340
341
342
343
344
345
346
347
348
349
350
351
Brett McLaughlin
Copyright © 2021 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-119-69618-6ISBN: 978-1-119-69616-2 (ebk)ISBN: 978-1-119-69621-6 (ebk)
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2020947753
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Kotlin is a registered trademark of Kotlin Foundation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
for Leigh, as always, my person
BRETT MCLAUGHLIN has been working and writing in the technology space for over 20 years. Today, Brett's focus is squarely on cloud and enterprise computing. He has quickly become a trusted name in helping companies execute a migration to the cloud—and in particular Amazon Web Services—by translating confusing cloud concepts into a clear executive-level vision. He spends his days working with key decision makers who need to understand the cloud as well as leading and building teams of developers and operators who must interact with the ever-changing cloud computing space. He has most recently led large-scale cloud migrations for NASA's Earth Science program and the RockCreek Group's financial platform. Brett is currently the Chief Technology Officer at Volusion, an ecommerce platform provider.
JASON LEE is a software developer happily living in the middle of the heartland. He has over 23 years of experience in a variety of languages, writing software running on mobile devices all the way up to big iron. For the past 15+ years, he has worked in the Java/Jakarta EE space, working on application servers, frameworks, and user-facing applications. These days, he spends his time working as a backend engineer, primarily using Kotlin, building systems with frameworks like Quarkus and Spring Boot. He is the author of Java 9 Programming Blueprints, a former Java User Group president, an occasional conference speaker, and a blogger. In his spare time, he enjoys spending time with his wife and two sons, reading, playing the bass guitar, and running. He can be found on Twitter at twitter.com/jasondlee, and on his blog at jasondl.ee.
I USED TO WATCH MOVIES AND STARE in amazement at the hundreds of names that scrolled by at the end. How could so many people be involved in a single movie?
Then I wrote a book. Now I understand.
Carole Jelen is my agent at Waterside, and she replied to an email and picked up the phone at a time when I really needed someone to help me find my way back into publishing. I'm incredibly grateful.
On the Wiley side, Brad Jones was more patient than he ever should have been. Thanks, Brad! Barath Kumar Rajasekaran handled a million tiny details, and Pete Gaughan and Devon Lewis kept the train on the tracks. Christine O'Connor handled production, and Jason Lee caught the technical mistakes in the text that you wouldn't want to stumble over. Seriously, Jason in particular made this a much better book with his keen eye.
As usual, it's an author's family that pays the highest price. Long days, more than a few weekends and evenings, and a constant support keep us going. My wife, Leigh, is the best, and my kids, Dean, Robbie, and Addie, always make finishing one of these a joy.
Let's do brunch, everyone! Mimosas and breakfast tacos are on me.
—BRETT MCLAUGHLIN
For decades, the Java programming language has been the dominant force in compiled languages. While there have been plenty of alternatives, it's Java that has remained core to so many applications, from desktop to server-side to mobile. This has become especially true for Android mobile development.
Finally, though, there is a real contender to at least live comfortably beside Java: Kotlin, a modern programming language shepherded by JetBrains (www.jetbrains.com). It is not Java, but is completely interoperable with it. Kotlin feels a lot like Java, and will be easy to learn for developers already familiar with the Java language, but offers several nice improvements.
Further, Kotlin is a full-blown programming language. It's not just for mobile applications, or a visual language that focuses on one specific application. Kotlin supports:
Inheritance, interfaces, implementations, and class hierarchies
Control and flow structures, both simple and complex
Lambdas and scope functions
Rich support for generics while still preserving strong typing
Idiomatic approaches to development, giving Kotlin a “feel” all its own
You'll also learn that while Kotlin is a new language, it doesn't feel particularly new. That's largely because it builds upon Java, and doesn't try to reinvent wheels. Rather, Kotlin reflects lessons that thousands of programmers coding in Java (and other languages) employ on a daily basis. Kotlin takes many of those lessons and makes them part of the language, enforcing strong typing and a strict compiler that may take some getting used to, but often produces cleaner and safer code.
There's also an emphasis in Kotlin, and therefore in this book, on understanding inheritance. Whether you're using packages from third parties, working with the standard Kotlin libraries, or building your own programs, you need a solid understanding of how classes interrelate, how subclassing works, and how to use abstract classes along with interfaces to define behavior and ensure that behavior is implemented. By the time you're through with this book, you'll be extremely comfortable with classes, objects, and building inheritance trees.
The Kotlin website (kotlinlang.org) describes Kotlin as “a modern programming language that makes developers happier.” With Kotlin and this book, you'll be happier and more productive in your Kotlin programming.
This book takes a holistic approach to teaching you the Kotlin programming language, from a beginner to a confident, complete Kotlin developer. By the time you're finished, you'll be able to write Kotlin applications in a variety of contexts, from desktop to server-side to mobile.
Yes, but you'll need more than just this book to build rich mobile applications in Kotlin. Kotlin is a rich language, and while there are books on all the packages needed to build mobile languages, this is fundamentally a book on learning Kotlin from the ground up. You'll get a handle on how Kotlin deals with generics, inheritance, and lambdas, all critical to mobile programming.
You can then take these concepts and extend them into mobile programming. You can easily add the specifics of Android-related packages to your Kotlin base knowledge, and use those mobile packages far more effectively than if you didn't have the fundamentals down.
If you are anxious to begin your mobile programming journey sooner, consider picking up a book focused on Kotlin mobile programming, and hop back and forth. Read and work through Chapter 1 of this book, and then do the same for the book focused on mobile programming. You'll have to context switch a bit more, but you'll be learning fundamentals alongside specific mobile techniques.
This book covers the following topics:
Chapter 1
: Objects All the Way Down
This chapter takes you from getting Kotlin installed to writing your first Kotlin program. You'll learn about functions from the start, and how to interact with the command line through a not-quite “Hello, World!” application. You'll also immediately begin to see the role of objects and classes in Kotlin, and refine your understanding of what a class is, what an object is, and what an object instance is.
Chapter 2
: It's Hard to Break Kotlin
This chapter delves into one of the distinguishing features of Kotlin: its rigid stance on type safety. You'll learn about Kotlin's types and begin to grasp choosing the right type for the right task. You'll also get familiar with
val
and
var
and how Kotlin allows for change.
Chapter 3
: Kotlin Is Extremely Classy
Like any object-oriented language, much of your work with Kotlin will be writing classes. This chapter digs into classes in Kotlin and looks at the basic building blocks of all Kotlin objects. You'll also override some functions and get deep into some of the most fundamental of Kotlin functions:
equals()
and
hashCode()
.
Chapter 4
: Inheritance Matters
This chapter begins a multichapter journey into Kotlin inheritance. You'll learn about Kotlin's constructors and the relatively unique concept of secondary constructors. You'll also learn more about the
Any
class, understand that inheritance is truly essential for all Kotlin programming, and learn why writing good superclasses is one of the most important skills you can develop in all your programming learning.
Chapter 5
: Lists and Sets and Maps, Oh My!
This chapter moves away (briefly) from classes and inheritance to add Kotlin collections to your arsenal. You'll use these collection classes over and over in your programming, so understanding how a
Set
is different from a
Map
, and how both are different from a
List
, is essential. You'll also dig further into Kotlin mutability and immutability—when data can and cannot change—as well as a variety of ways to iterate over collections of all types.
Chapter 6
: The Future (in Kotlin) Is Generic
Generics are a difficult and nuanced topic in most programming languages. They require a deep understanding of how languages are built. This chapter gets into those depths, and provides you more flexibility in building classes that can be used in a variety of contexts than possible without generics. You'll also learn about covariance, contravariance, and invariance. These might not be the hot topics at the water cooler, but they'll be key to building programs that use generics correctly, and also level up your understanding of inheritance and subclassing.
Chapter 7
: Flying through Control Structures
Control structures are the bread and butter of most programming languages. This chapter breaks down your options, covering
if
and
else
,
when
,
for
,
while
, and
do
. Along the way, you'll focus on controlling the flow of an application or set of applications all while getting a handle on the semantics and mechanics of these structures.
Chapter 8
: Data Classes
This chapter introduces data classes, another very cool Kotlin concept. While not specific to only Kotlin, you'll find that data classes offer you a quick and flexible option for representing data more efficiently than older languages. You'll also really push data classes, going beyond a simple data object and getting into constructors, overriding properties, and both subclassing with and extending from data classes.
Chapter 9
: Enums and Sealed, More Specialty Classes
This chapter introduces enums, a far superior approach to
String
constants. You'll learn why using
String
s for constant values is a really bad idea, and how enums give you greater flexibility and type safety, as well as making your code easier to write. From enums, you'll move into sealed classes, a particularly cool feature of Kotlin that lets you turbo-charge the concept of enums even further. You'll also dig into companion objects and factories, all of which contribute to a robust type-safe approach to programming where previously only
String
types were used.
Chapter 10
: Functions and Functions and Functions
It may seem odd to have a chapter this late in the book that purports to focus on functions. However, as with most fundamentals in any discipline, you'll have to revisit the basics over and over again, shoring up weaknesses and adding nuance. This chapter does just that with functions. You'll dig more deeply into just how arguments really work, and how many options Kotlin provides to you in working with data going into and out of your functions.
Chapter 11
: Speaking Idiomatic Kotlin
Kotlin, like all programming languages, has certain patterns of usage that seasoned programmers revert to time and time again. This chapter discusses these and some of the idioms of Kotlin. You'll get a jump start on writing Kotlin that looks like Kotlin is “supposed to” all while understanding how you have a tremendous amount of flexibility in choosing how to make your Kotlin programs feel like “you.”
Chapter 12
: Inheritance, One More Time, with Feeling
Yes, it really is another chapter on inheritance! This chapter takes what you've already learned about abstract classes and superclasses and adds interfaces and implementations into the mix. You'll also learn about the delegation pattern, a common Kotlin pattern that helps you take inheritance even further with greater flexibility than inheritance alone provides.
Chapter 13
: Kotlin: The Next Step
No book can teach you everything you need to know, and this book is certainly no exception. There are some well-established places to look for next steps in your Kotlin programming journey, though, and this chapter gives you a number of jumping-off points to continue learning about specific areas of Kotlin.
As you work through the examples in this book, the project files you need are available for download from www.wiley.com/go/programmingkotlinapplications.
If you believe you've found a mistake in this book, please bring it to our attention. At John Wiley & Sons, we understand how important it is to provide our customers with accurate content, but even with our best efforts an error may occur.
In order to submit your possible errata, please email it to our Customer Service Team at [email protected] with the subject line “Possible Book Errata Submission.”
We appreciate your input and questions about this book! Email me at [email protected], or DM me on Twitter at @bdmclaughlin.
