(FREE PDF Sample) Kotlin Apprentice Second Edition Beginning Programming With Kotlin Irina Galata Ebooks
(FREE PDF Sample) Kotlin Apprentice Second Edition Beginning Programming With Kotlin Irina Galata Ebooks
com
https://textbookfull.com/product/kotlin-apprentice-second-
edition-beginning-programming-with-kotlin-irina-galata/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/android-apprentice-second-edition-
beginning-android-development-with-kotlin-darryl-bayliss/
textboxfull.com
https://textbookfull.com/product/android-apprentice-fourth-edition-
beginning-android-development-with-kotlin-namrata-bandekar/
textboxfull.com
https://textbookfull.com/product/programming-kotlin-applications-
building-mobile-and-server-side-applications-with-kotlin-1st-edition-
brett-mclaughlin/
textboxfull.com
https://textbookfull.com/product/programming-kotlin-enhance-your-
skills-for-android-development-using-kotlin-2nd-edition-alexander-
aronowitz/
textboxfull.com
Programming Android With Kotlin: Achieving Structured
Concurrency With Coroutines Pierre-Olivier Laurence
https://textbookfull.com/product/programming-android-with-kotlin-
achieving-structured-concurrency-with-coroutines-pierre-olivier-
laurence/
textboxfull.com
https://textbookfull.com/product/programming-dsls-in-kotlin-1st-
edition-venkat-subramaniam-subramaniam/
textboxfull.com
https://textbookfull.com/product/reactive-programming-with-kotlin-
first-edition-learn-rx-with-rxjava-rxkotlin-and-rxandroid-alex-
sullivan/
textboxfull.com
https://textbookfull.com/product/kotlin-programming-the-big-nerd-
ranch-guide-1st-edition-josh-skeen/
textboxfull.com
Kotlin Appren,ce
By Irina Galata, Joe Howard & Ellen Shapiro
No,ce of Rights
All rights reserved. No part of this book or corresponding materials (such as text,
images, or source code) may be reproduced or distributed by any means without
prior written permission of the copyright owner.
No,ce of Liability
This book and all corresponding materials (such as source code) are provided on an
“as is” basis, without warranty of any kind, express of implied, including but not
limited to the warranties of merchantability, fitness for a particular purpose, and
noninfringement. In no event shall the authors or copyright holders be liable for any
claim, damages or other liability, whether in action of contract, tort or otherwise,
arising from, out of or in connection with the software or the use of other dealing in
the software.
Trademarks
All trademarks and registered trademarks appearing in this book are the property of
their own respective owners.
raywenderlich.com 2
Kotlin Apprentice
Joe Howard is an author and final pass editor of this book. Joe is a
computational physicist who studied particle physics using parallel
Fortran simulations. He gradually shifted into systems engineering
and ultimately software engineering around the time of the release
of the iOS and Android SDKs. He's been a mobile software
developer on iOS and Android since 2009, working primarily at two
agencies in Boston, MA since 2011. He's now the Android Pillar
Lead for raywenderlich.com. Twitter: @orionthewake.
raywenderlich.com 3
Kotlin Apprentice
Acknowledgements
We’d also like to acknowledge the efforts of the authors of the Swift Apprentice and
previous editions of Kotlin Apprentice whose work formed the basis for parts of this
book:
• Janie Clayton is an independent iOS developer. She spent a year apprenticed to a
super genius programming robots and learning the forgotten ways of long term
software maintenance and development. Janie is the coauthor on several books on
iOS and Swift development. Janie lives outside of Madison, Wisconsin with her
attempted grumble of pugs and multitude of programming books. Janie writes her
various musings on her blog at RedQueenCoder.com.
• Alexis Gallagher is a software engineer who is always looking for the conceptual
deep dive and always hoping to find pearls down at the bottom. When he’s not
coding, he’s out and about in sunny San Francisco.
• Matt Galloway is a software engineer with a passion for excellence. He stumbled
into iOS programming when it first was a thing, and has never looked back. When
not coding, he likes to brew his own beer.
• Eli Ganim is an engineering manager at Facebook. He is passionate about
teaching, writing, and sharing his knowledge with others.
• Erik Kerber is a software developer in Minneapolis, MN, and the lead iOS
developer for the Target app. He does his best to balance a life behind the
keyboard with cycling, hiking, scuba diving, and traveling.
• Ben Morrow delights in discovering the unspoken nature of the world. He’ll tell
you the surprising bits while on a walk. He produces beauty by drawing out the raw
wisdom that exists within each of us.
• Cosmin Pupăză is a software developer and tutorial writer from Romania. He has
worked with more than a dozen programming languages over the years, but none
of them has made such a great impact on himself as the advent of Swift. When not
coding, he either plays the guitar or studies WWII history. Cosmin blogs about
Swift at cosminpupaza.wordpress.com.
• Steven Van Impe is a computer science lecturer at the University College of
Ghent, Belgium. When he’s not teaching, Steven can be found on his bike, rattling
over cobblestones and sweating up hills, or relaxing around the table, enjoying
board games with friends. You can find Steven on Twitter as @svanimpe.
• Dick Lucas is a developer by trade but adds value anyway he can. He is also a
writer, podcast host, and advisor at nogradient.com. He thinks most things are
superfluous.
raywenderlich.com 4
Kotlin Apprentice
raywenderlich.com 5
Kotlin Apprentice
Dedica,ons
"To my fiancée Lilia, for all her support, encouragement, and
patience. Love you. ! "
—Ellen Shapiro
—Irina Galata
"To Lauren."
—Joe Howard
raywenderlich.com 6
Kotlin Apprentice
raywenderlich.com 7
Kotlin Apprentice
raywenderlich.com 8
Kotlin Apprentice
raywenderlich.com 9
Kotlin Apprentice
Strings in Kotlin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Pairs and Triples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Number types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Any, Unit, and Nothing Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Chapter 4: Basic Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . 80
Comparison operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
The if expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Chapter 5: Advanced Control Flow . . . . . . . . . . . . . . . . . . . . . 97
Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
when expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Chapter 6: Func7ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Func7on basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Func7ons as variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Chapter 7: Nullability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Introducing null . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Introducing nullable types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
raywenderlich.com 10
Kotlin Apprentice
raywenderlich.com 11
Kotlin Apprentice
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Chapter 10: Lambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Lambdas basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Custom sor7ng with lambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Itera7ng over collec7ons with lambdas . . . . . . . . . . . . . . . . . . . . . . . . 169
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
raywenderlich.com 12
Kotlin Apprentice
raywenderlich.com 13
Kotlin Apprentice
raywenderlich.com 14
Kotlin Apprentice
raywenderlich.com 15
Kotlin Apprentice
raywenderlich.com 16
Kotlin Apprentice
raywenderlich.com 17
I Introduc,on
The Kotlin language has been around since 2011, but its popularity took off in 2017
when Google announced Kotlin’s inclusion as a first-class language for Android
development. In 2019, Google announced a "Kotlin-first" approach to Android
development. With modern and expressive language characteristics such as those
found in Apple’s Swift, and 100% interoperability with Java, it’s no wonder that
Kotlin has been named a top 5 most-loved language by Stack Overflow users.
If you're a complete beginner to programming, this is the book for you! There are
short exercises and challenges throughout the book to give you some programming
practice and test your knowledge along the way.
Through Kotlin Apprentice, you'll learn about basic things like constants, values and
types, move up to more complicated items such as data structures, classes and
enumerators, and finish off with some in-depth knowledge about functional
programming, coroutines, and Kotlin Multiplatform.
If you want to get right into Android app development after you work through Kotlin
Apprentice, we suggest you read the Android Apprentice, available on our store:
• https://store.raywenderlich.com/products/android-apprentice
The Android Apprentice is your introduction to building great apps in Android, using
the Kotlin language, for both novice programmers and those with extensive
experience programming for iOS or other platforms.
It will help you master the essential building blocks of Kotlin and Android to start
creating apps. As you work on more apps, you'll find the foundations you learn in
Kotlin Apprentice and Android Apprentice will give you the knowledge you need to
easily figure out more complicated details on your own.
raywenderlich.com 18
L Book License
• You are allowed to use and/or modify the source code in Kotlin Apprentice in as
many apps as you want, with no attribution required.
• You are allowed to use and/or modify all art, images and designs that are included
in Kotlin Apprentice in as many apps as you want, but must include this attribution
line somewhere inside your app: “Artwork/images/designs: from Kotlin Apprentice,
available at www.raywenderlich.com”.
• The source code included in Kotlin Apprentice is for your personal use only. You are
NOT allowed to distribute or sell the source code in Kotlin Apprentice without prior
authorization.
• This book is for your personal use only. You are NOT allowed to sell this book
without prior authorization, or distribute it to friends, coworkers or students; they
would need to purchase their own copies.
All materials provided with this book are provided on an “as is” basis, without
warranty of any kind, express or implied, including but not limited to the warranties
of merchantability, fitness for a particular purpose and noninfringement. In no event
shall the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from, out of or in
connection with the software or the use or other dealings in the software.
All trademarks and registered trademarks appearing in this guide are the properties
of their respective owners.
raywenderlich.com 19
B Book Source Code &
Forums
https://store.raywenderlich.com/products/kotlin-apprentice-source-code
Forums
We’ve also set up an official forum for the book at forums.raywenderlich.com. This is
a great place to ask questions about the book or to submit any errors you may find.
Buying the digital edition version of the book also has a few extra benefits: free
updates each time we update the book, access to older versions of the book, and you
can download the digital editions from anywhere, at anytime.
raywenderlich.com 20
Kotlin Apprentice Book Source Code & Forums
• https://store.raywenderlich.com/products/kotlin-apprentice.
And if you purchased the print version of this book, you’re eligible to upgrade to the
digital editions at a significant discount! Simply email [email protected] with
your receipt for the physical copy and we’ll get you set up with the discounted digital
edition version of the book.
raywenderlich.com 21
W What You Need
• Kotlin Plugin for IntelliJ IDEA v1.3.40 or later, installed (if not included by
default) by going to IntelliJ IDEA Preferences on macOS (or Settings on
Windows/Linux) and choosing Plugins, then searching on "Kotlin".
• Java SE Development Kit 8 or later. Most of the code in this book will be run on
the Java Virtual Machine or JVM, for which you need a Java Development Kit or
JDK. The JDK can be downloaded from Oracle at http://www.oracle.com/
technetwork/java/javase/downloads/index.html.
• In Chapters 24 and 25, you'll have the option of using a text editor such as Visual
Studio Code instead of IntelliJ IDEA.
• In Chapter 26, in place of IntelliJ IDEA, you'll use Android Studio 3.5 or later and
Xcode 10.3 or later to build a Kotlin Multiplatform app.
If you haven't installed the latest versions of IntelliJ IDEA Community Edition, the
Kotlin Plugin, and JDK 8, be sure to do that before continuing with the book. Chapter
1: "Your Kotlin Development Environment" will show you how to get started with
IntelliJ IDEA to run Kotlin code on the JVM.
raywenderlich.com 22
A About the Cover
The parrot has long captured the eye and imagination of humans; from Aesop to
Monty Python, from ancient Peruvians to swashbuckling pirates, the beautiful
plumage of parrots have made them a recurring theme throughout history.
The expressiveness and mimicry of parrots is very much akin to Kotlin; Kotlin takes
the best of many languages and “mimics" those languages in a modern and
expressive way. Although Kotlin won’t whistle a tune or ride on your shoulder when
you cosplay Long John Silver, Kotlin will still be a great companion to you as you sail
the seven seas of programming!
raywenderlich.com 23
Sec,on I: Kotlin Basics
The chapters in this section will introduce you to the very basics of programming in
Kotlin. From the fundamentals of how computers work, all the way up to language
structures, you’ll cover enough of the language to be able to work with data and
organize your code’s behavior.
• Chapter 2, Expressions, Variables & Constants: You'll need to learn some basics
about how code works so that you can begin programming in Kotlin. You’ll begin
with an overview of computers and programming. You’ll learn some basics such as
code comments, arithmetic operations, constants and variables. These are some of
the fundamental building blocks of any language, and Kotlin is no different.
• Chapter 3, Types & Operations: You’ll learn about handling different types,
including strings, which allow you to represent text. You’ll learn about converting
between types, and you’ll also be introduced to type inference, which makes your
life as a programmer a lot simpler. You’ll learn how to group multiple values of any
type into pairs and triples.
raywenderlich.com 24
Kotlin Apprentice Section I: Kotlin Basics
Once you have the basic data types in your head, it’ll be time to do things with that
data:
• Chapter 4, Basic Control Flow: Because your computer doesn't know what to do
unless you tell it, you'll need to understand how to control the flow of a program
by various methods. You’ll learn how to make decisions and repeat tasks in your
programs by using syntax to control the flow. You’ll also learn about Booleans,
which represent true and false values, and how you can use these to compare data.
And, finally, you'll learn about loops, which are Kotlin’s way of executing code
multiple times.
• Chapter 5, Advanced Flow Control: Continuing the theme of code not running
in a straight line, you’ll learn about another loop known as the for loop. And,
you'll learn about when expressions, which are particularly powerful in Kotlin; they
let you inspect a value and decide what to do based on that value. They’re
incredibly powerful when used with pattern matching.
• Chapter 6, Functions: Functions are the basic building blocks you use to
structure your code in Kotlin. You’ll learn how to define functions to group your
code into reusable units.
And, finally, you'll move past the variables and constants you've been working with,
which have had concrete values:
• Chapter 7, Nullability: You'll learn about nullable types, with which you can
represent a value but also the absence of a value. They can be tricky but, by the end
of the chapter, you'll know why you would use nullable types and when best to use
them effectively.
These fundamentals will get you on your way and, before you know it, you’ll be ready
for the more advanced topics that follow. Let’s get started!
raywenderlich.com 25
1 Chapter 1: Your Kotlin
Development Environment
By Joe Howard
Then, you’ll write your very first Kotlin code and see how to run the code on your
machine.
The primary tool that you’ll use in this book to create Kotlin projects is IntelliJ IDEA
from JetBrains. JetBrains is also the company behind the Kotlin language itself, so
Kotlin development is very tightly integrated into IntelliJ IDEA.
You use an IDE to write code in an editor, compile the code into a form that can be
run on your computer, see output from your program, fix issues in your code and
much more! You’ll just scratch the surface of the power of IntelliJ IDEA in this
chapter, but you’ll be setup to work with the code examples throughout the rest of
the book.
raywenderlich.com 26
Kotlin Apprentice Chapter 1: Your Kotlin Development Environment
Go ahead and download IntelliJ IDEA 2019.2 or later on your platform of choice.
There are versions for macOS, Windows and Linux. Follow the installation
instructions on the JetBrains site to install IntelliJ IDEA on your machine. Most of
the screenshots in this book will be from the macOS version, but the Windows and
Linux versions are similar.
Before you first run IntelliJ IDEA, you’ll also want to install a Java Development
Kit, or JDK, which will easily let you run Kotlin code on your machine.
In many ways, Kotlin was initially created as a modern replacement for the Java
programming language. Java was created in the 1990’s as an early attempt at a cross-
platform application language, promising a "Write Once, Run Everywhere" approach
to software development.
Instead of compiling to native machine code on each platform, Java programs are
compiled into a format called bytecode. The bytecode runs inside an application on
the Java Virtual Machine. The JVM can be thought of as a layer above your actual
machine. By running as bytecode on a virtual machine, you are able to share Java
code and applications across many types of computer systems.
Most of the code and projects in this book are meant to be run as Kotlin projects on
the JVM. In order to do so, you must install the JDK alongside IntelliJ IDEA. The
easiest way to get a JDK for your platform is to visit the Oracle website at:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
raywenderlich.com 27
Kotlin Apprentice Chapter 1: Your Kotlin Development Environment
You’ll want to download and install the latest version of the JDK — at least version 8.
The Java software tools go by the name "Java SE," which includes the JDK and also
the Java Runtime Environment, or JRE.
Note: Be sure to download and install the JDK and not just the JRE, since the
JRE only lets you run Java applications and does not include the tools to build
new ones.
If you’ve installed previous versions of IntelliJ IDEA on the same machine, the
installer will likely prompt you to import settings from a previous version. If you’ve
not installed previous versions on the same machine, you’ll be prompted to choose a
color theme and choose plugins to install into the IDE. You can just choose the
default settings and proceed.
From the welcome window, you can create new projects, import or open existing
projects, check out code from a version control system such as Git, run configuration
tools and get help on the IDE.
raywenderlich.com 28
Kotlin Apprentice Chapter 1: Your Kotlin Development Environment
Choose Kotlin in the list of options on the left and Kotlin JVM as the project type
and click Next.
You then see a screen for the project name and location. You also see the Project
SDK, which should be the JDK version that you installed earlier — or a different JDK
version if you have more than one installed on your machine.
raywenderlich.com 29
Exploring the Variety of Random
Documents with Different Content
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project
Gutenberg™ works in compliance with the terms of this
agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms
of this agreement by keeping this work in the same format with
its attached full Project Gutenberg™ License when you share it
without charge with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must, at
no additional cost, fee or expense to the user, provide a copy, a
means of exporting a copy, or a means of obtaining a copy upon
request, of the work in its original “Plain Vanilla ASCII” or other
form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com