Table Of ContentMastering Kotlin
Mastering Kotlin helps readers quickly understand core concepts and then move
on to practical projects using the Kotlin programming language.
Back in the day, Java was the de facto choice for creating Android apps. How-
ever, since Google announced Kotlin as the new language of choice for building
Android applications, developers haven’t looked back.
Kotlin is a general-purpose, statically typed, open source programming language
that runs on Java Virtual Machines. It can be called a Java replacement; however,
the Kotlin syntax isn’t blindly identical to that of Java. Sure, Kotlin can work with
Java, and owing to its intuitiveness, it can also enhance overall productivity and
efficiency, but it is not a Java clone.
Kotlin differs from Java in that it has assertive interfaces that help determine variables
and expressions classes, even if they’re not defined. Kotlin is a beautiful alternative
for modifying and identifying faults because it has a familiar and straightforward
syntax and programming structure. It comes with a sophisticated compiler that can
track automatic casts, allowing verification durations to be more efficient. Kotlin
also has simple signals that may be interpreted without any need for set parameters.
And Kotlin is easy to set up: all you need is a Kotlin component for Android Studio.
Kotlin developers are in high demand. As a Kotlin developer, you’ll be able to pur-
sue a variety of career routes, spanning fields such as mobile app dev, game dev,
game design, and even software development. Many well-known brands use Kotlin
in their software and projects. Naturally, it is a good idea to learn Kotlin, and this
is where Mastering Kotlin can be the right manual for you!
With Mastering Kotlin, learning Kotlin becomes an easy task, and learners can use
their skills to create innovative Kotlin apps.
The Mastering Computer Science series is edited by Sufyan bin Uzayr, a writer and
educator with over a decade of experience in the computing field.
Mastering Computer Science
Series Editor: Sufyan bin Uzayr
Mastering Kotlin: A Beginner’s Guide
Divya Sachdeva, Faruq KC, and Aruqqa Khateib
Mastering KDE: A Beginner’s Guide
Jaskiran Kaur, Mathew Rooney, and Shahryar Raz
Mastering GNOME: A Beginner’s Guide
Jaskiran Kaur, Mathew Rooney, and Reza Nafim
Mastering Flutter: A Beginner’s Guide
Divya Sachdeva, NT Ozman, and Reza Nafim
Mastering Visual Studio Code: A Beginner’s Guide
Jaskiran Kaur, D Nikitenko, and Mathew Rooney
Mastering Ubuntu: A Beginner’s Guide
Jaskiran Kaur, Rubina Salafey, and Shahryar Raz
For more information about this series, please visit: https://www.routledge
.com/Mastering-Computer-Science/book-series/MCS
The “Mastering Computer Science” series of books are authored by the
Zeba Academy team members, led by Sufyan bin Uzayr.
Zeba Academy is an EdTech venture that develops courses and content
for learners primarily in STEM fields, and offers education consulting
to Universities and Institutions worldwide. For more info, please visit
https://zeba.academy.
Mastering Kotlin
A Beginner’s Guide
Edited by
Sufyan bin Uzayr
First Edition published 2023
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
and by CRC Press
2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2023 Sufyan bin Uzayr
Reasonable efforts have been made to publish reliable data and information, but the author and
publisher cannot assume responsibility for the validity of all materials or the consequences of their use.
The authors and publishers have attempted to trace the copyright holders of all material reproduced in
this publication and apologize to copyright holders if permission to publish in this form has not been
obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced,
transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or
hereafter invented, including photocopying, microfilming, and recording, or in any information
storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com
or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf.
co.uk
Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.
Library of Congress Cataloging‑in‑Publication Data
Names: Bin Uzayr, Sufyan, editor.
Title: Mastering Kotlin : a beginner’s guide / edited by Sufyan bin Uzayr.
Description: First edition. | Boca Raton : CRC Press, 2023. |
Series: Mastering computer science | Includes bibliographical references and index.
Identifiers: LCCN 2022021392 (print) | LCCN 2022021393 (ebook) | ISBN
9781032318950 (hardback) | ISBN 9781032318851 (paperback) | ISBN
9781003311904 (ebook)
Subjects: LCSH: Android (Electronic resource) | Kotlin (Computer program
language) | Application software--Development. | Mobile apps--Development. |
Java (Computer program language)
Classification: LCC QA76.73.K68 M37 2023 (print) | LCC QA76.73.K68
(ebook) | DDC 005.4/45--dc23/eng/20220810
LC record available at https://lccn.loc.gov/2022021392
LC ebook record available at https://lccn.loc.gov/2022021393
ISBN: 9781032318950 (hbk)
ISBN: 9781032318851 (pbk)
ISBN: 9781003311904 (ebk)
DOI: 10.1201/9781003311904
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
Preface, xix
About the Author, xxi
Chapter 1 ◾ G etting Started 1
HISTORY OF KOTLIN 2
FEATURES OF KOTLIN 2
KOTLIN’S KEY CHARACTERISTICS 2
HOW KOTLIN MULTIPLATFORM FUNCTIONS 5
KOTLIN’S ARCHITECTURE 6
KOTLIN VS. JAVA 7
KOTLIN MULTIPLATFORM IN MOBILE 9
Begin with Kotlin Multiplatform Mobile 9
Platforms That Are Supported 9
Kotlin for Server-Side 10
Kotlin Frameworks for Server-Side Development 10
Using Kotlin to Deploy Server-Side Apps 11
Kotlin for Android 11
Kotlin for JavaScript (JS) 12
Frameworks in Kotlin/JS 12
Kotlin/Native 13
Why Is Kotlin/Native Used? 13
Kotlin for Data Science 14
Editors Who Work Interactively 14
Kotlin for Competitive Programming 14
v
vi ◾ Contents
Kotlin Language Applications 15
Setup of the Kotlin Environment for Command Line 15
Intellij IDEA Is Used to Build up a Kotlin Environment 15
Kotlin Hello Everyone Program 16
DATA TYPES IN KOTLIN 18
Integer Data Type 18
Floating-Point Data Type 19
Boolean Data Type 20
Character Data Type 20
VARIABLES IN KOTLIN 20
Immutable Using val Keyword 21
Variable Scope 21
Naming Convention 22
OPERATORS IN KOTLIN 22
Arithmetic Operator 22
Relation Operator 23
Assignment Operator 23
Unary Operator 24
Logical Operator 24
Bitwise Operator 25
KOTLIN STANDARD INPUT/OUTPUT 25
Distinction between println() and print() 26
Variables and Literals Print 26
Input of Kotlin 27
Take User Input with the readline() Function 27
Take Input from the User Using the Scanner Class 27
Take User Input without Using the Scanner Class 28
TYPE CONVERSION IN KOTLIN 29
Conversion of a Larger Data Type to a Smaller Data Type 30
EXPRESSION, STATEMENT, AND BLOCK IN KOTLIN 30
Expression in Kotlin 30
Kotlin if Expression 31
Contents ◾ vii
Statement in Kotlin 31
Multiple Statements in Kotlin 32
Block in Kotlin 32
Variable Scope in Nested Blocks 33
CONCLUSION 33
Chapter 2 ◾ O bject-Oriented Programming (OOP)
Concepts 35
OBJECTS AND CLASSES IN KOTLIN 35
Language for Object-Oriented Programming 36
Class 36
Object 37
NESTED CLASS AND INNER CLASS IN KOTLIN 39
Nested Class 39
In Comparison to Java 40
Kotlin Inner Class 41
Inner-Class Kotlin Program 41
SETTERS AND GETTERS IN KOTLIN 42
Setters and Getters 43
Default Setter and Getter Kotlin Program 44
Identifiers for Values and Fields 44
Private Modifier 44
Setter and Getter with Custom Parameters 45
CLASS PROPERTIES AND CUSTOM ACCESSORS IN KOTLIN 46
Property 47
Customer Accessors 48
KOTLIN CONSTRUCTOR 48
Primary Constructor 49
Primary Constructor with Initializer Block 50
Secondary Constructor 51
KOTLIN VISIBILITY MODIFIERS 54
Public Modifier 55
Private Modifier 56
viii ◾ Contents
Internal Modifier 56
Protected Modifier 57
Overriding of Protected Modifier 57
Constructor Visibility 58
INHERITANCE IN KOTLIN 58
Inheritance Use 60
Primary Constructor for Kotlin Inheritance 62
Secondary Constructor for Kotlin Inheritance 63
Overriding Member Functions and Properties 64
Calling the Superclass Implementation 65
INTERFACES IN KOTLIN 66
Interfaces Creating 66
Default Methods and Default Values 67
Interface Properties 68
Interface Inheritance 69
Implementation of Multiple Interfaces 70
DATA CLASSES IN KOTLIN 71
Data Class Creation Rules 72
toString() 72
copy() 73
hashCode() and equals() 75
KOTLIN SEALED CLASSES 76
Sealed Class with When 77
KOTLIN ABSTRACT CLASS 78
Multiple Derived Classes 81
ENUM CLASSES IN KOTLIN 82
Enums Initializing 83
Enums Properties and Methods 83
Properties and Functions of the Enum Class 84
Enums as Anonymous Classes 85
Usage of When Expression with Enum Class 86
Contents ◾ ix
KOTLIN EXTENSION FUNCTION 86
Extended Library Class Using an Extension Function 87
Extensions Are Resolved Statically 88
Nullable Receiver 89
Companion Object Extensions 89
KOTLIN GENERICS 91
Generic Usage in Our Program 91
VARIANCE 92
The out Keyword 93
The in Keyword 93
COVARIANCE 94
CONTRACOVARIANCE 94
TYPE PROJECTIONS 95
STAR PROJECTIONS 95
CONCLUSION 95
Chapter 3 ◾ E xceptional Handling, Null Safety,
and Regex and Ranges 97
EXCEPTIONAL HANDLING IN KOTLIN | TRY, CATCH,
THROW, AND FINALLY 97
Exceptions in Kotlin 98
What If We Don’t Handle Exceptions? 99
How to Throw an Exception in Kotlin 99
How to Avoid NullPointerException 100
KOTLIN TRY-CATCH BLOCK 101
Kotlin Try-Catch Block as an Expression 102
Kotlin Finally Block 102
Kotlin Throw Keyword 104
NESTED TRY BLOCK AND MULTIPLE CATCH
BLOCK IN KOTLIN 104
Nested Try Block 104
Multiple Catch Block 105