Kotlin The Ultimate Guide (Sufyan bin Uzayr) (Z-Library)

Author: Sufyan bin Uzayr

技术

Kotlin is a free and open-source general purpose programming language that is mostly used to create Android apps. Kotlin was developed by JetBrains initially and later picked up by Google as the language of choice for its Android platform. Over the past few years, Kotlin has become one of the most popular alternatives to Java language and is used by more than 80 percent of Android app developers. Kotlin is a statically typed, advanced programming language that compiles Kotlin code into Java byte-code and runs on a Java Virtual Machine (JVM). It can also be compiled to native executables and JavaScript source code. It is an object-oriented programming language that includes data types, operators, I/O comments, control statements, functions, classes, object expressions, and constructors, among other features. It is not a standalone programming language; rather, it is an innovative manner of coding that runs on Java. Kotlin is a versatile language with some cool features like compatibility, low runtime, and efficient coding characteristics. The features that help distinguish Kotlin from other languages are its reliability, tool support, and interoperability. It is a simplified version of Java that is much easier to deal with. Why Should You Learn Kotlin? The popularity of Kotlin is growing, and will continue to do so in the coming years. Kotlin has always been -- and will continue to be -- a cutting-edge programming language that meets the needs of real professionals. Many emerging fields, including mobile, online gaming, server-side, cloud development, data science, and education, are progressively using Kotlin. All of this indicates that there is already a high demand for Kotlin developers, and that demand will continue to grow in the future. Furthermore, if you are looking to build native Android apps, Kotlin is the language that you should be using.

📄 File Format: PDF
💾 File Size: 7.6 MB
45
Views
0
Downloads
0.00
Total Donations

📄 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.

📄 Page 1
(This page has no text content)
📄 Page 2
Kotlin Kotlin is a free and open-source general-purpose programming language that is mostly used to create Android apps. Kotlin was developed by JetBrains initially and later picked up by Google as the language of choice for its Android platform. Over the past few years, Kotlin has become one of the most popular alternatives to Java language and is used by more than 80 percent of Android app developers. Kotlin is a statically typed, advanced programming language that compiles Kotlin code into Java byte-code and runs on a Java Virtual Machine (JVM). It can also be compiled to native executables and JavaScript source code. It is an object-oriented programming language that includes data types, operators, I/O comments, control statements, functions, classes, object expressions, and constructors, among other features. It is not a standalone programming language; rather, is an innovative manner of coding that runs on Java. Kotlin is a versatile language with some interesting and cool features like compat- ibility, low runtime, and efficient coding characteristics. The features that help dis- tinguish Kotlin from other languages are its reliability, tool support, and interoper- ability. It is a simplified version of Java that is much easier to deal with. Why Should You Learn Kotlin? The popularity of Kotlin is growing, and it will continue to do so in the coming years. Kotlin has always been, and will continue to be, a cutting-edge program- ming language that best meets the needs of real professionals. Many emerging fields, including mobile, online gaming, server-side, cloud development, data science, and education, are progressively using Kotlin. All of this indicates that there is already a high demand for Kotlin developers, and that demand will continue to grow in the future. Furthermore, if you are looking to build native Android apps, Kotlin is the language that you should be using.
📄 Page 3
(This page has no text content)
📄 Page 4
Kotlin The Ultimate Guide Edited by Sufyan bin Uzayr
📄 Page 5
First edition published 2023 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 4 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, author. Title: Kotlin : the ultimate guide / Sufyan bin Uzayr. Description: First edition. | Boca Raton : CRC Press, 2023. | Includes bibliographical references and index. Identifiers: LCCN 2022025675 (print) | LCCN 2022025676 (ebook) | ISBN 9781032311708 (hardback) | ISBN 9781032311692 (paperback) | ISBN 9781003308447 (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 B56 2023 (print) | LCC QA76.73.K68 (ebook) | DDC 005.1/14--dc23/eng/20220917 LC record available at https://lccn.loc.gov/2022025675 LC ebook record available at https://lccn.loc.gov/2022025676 ISBN: 9781032311708 (hbk) ISBN: 9781032311692 (pbk) ISBN: 9781003308447 (ebk) DOI: 10.1201/9781003308447 Typeset in Minion by KnowledgeWorks Global Ltd.
📄 Page 6
v Contents Acknowledgments, xxi About the Author, xxiii Chapter 1 ◾ Crash Course in Kotlin 1 KOTLIN PROGRAMMING LANGUAGE HAS A RICH HISTORY 2 FEATURES OF THE KOTLIN PROGRAMMING LANGUAGE 2 KOTLIN PROGRAMMING LANGUAGE APPLICATIONS 4 WHY SHOULD WE STUDY THE KOTLIN PROGRAMMING LANGUAGE? WHAT ARE THE BENEFITS OF LEARNING THE KOTLIN PROGRAMMING LANGUAGE? 4 DISADVANTAGES OF KOTLIN 5 WHAT IS THE PURPOSE OF KOTLIN? 5 Android Development 5 Back-End Web Development 6 Full-Stack Web Development 6 Data Science 6 Mobile Development for Several Platforms 7 KOTLIN’S ARCHITECTURE 7 KOTLIN FRAMEWORKS FOR SERVER-SIDE DEVELOPMENT 8 KOTLIN ENVIRONMENT FOR COMMAND LINE SETUP 9 Intellij IDEA IS USED TO BUILD UP A KOTLIN ENVIRONMENT 9 THE FIRST PROGRAM IS WRITTEN IN KOTLIN 11 KOTLIN DATA TYPES 12 Number Data Types in Kotlin 12 Character Data Type in Kotlin 13
📄 Page 7
vi ◾ Contents String Data Type in Kotlin 14 Boolean Data Type in Kotlin 14 Array Data Type in Kotlin 15 DATA TYPE CONVERSION IN KOTLIN 15 OPERATORS IN KOTLIN 16 Arithmetic Operators in Kotlin 16 Relational Operators in Kotlin 17 Assignment Operators in Kotlin 17 Unary Operators in Kotlin 18 Logical Operators in Kotlin 19 Bitwise Operations in Kotlin 19 BOOLEANS IN KOTLIN 20 Create Boolean Variables 20 Boolean Operators in Kotlin 21 Boolean Expression in Kotlin 21 and() and or() Functions in Kotlin 22 Boolean to String 22 STRINGS IN KOTLIN 22 String Templates in Kotlin 23 String Object in Kotlin 23 String Indexes in Kotlin 23 String Length in Kotlin 24 String Kotlin Last Index 24 String Case Changing 24 String Concatenation in Kotlin 25 Trim Characters from the String 25 Quotes Inside a String 26 Finding a String Inside a String 26 Comparing Two Strings 26 getOrNull() Function in Kotlin 26 toString() Function in Kotlin 27
📄 Page 8
Contents ◾ vii ARRAYS IN KOTLIN 27 Creating Arrays 27 Arrays of the Primitive Type 28 Elements of an Array Can Be Get and Set 28 Array Length in Kotlin 28 Loop through an Array 29 Check if an Element Exists 29 Distinct Values from the Array 29 Dropping Elements from the Array 30 Checking an Empty Array 30 RANGES IN KOTLIN 30 Creating Ranges Using the rangeTo() Function 31 Creating the Ranges Using the .. Operator 31 Creating the Ranges Using downTo() Operator 31 step() Function in Kotlin 32 Range of Characters in Kotlin 32 reversed() Function in Kotlin 32 until() Function in Kotlin 32 The last, first, and step Elements 33 Filtering Ranges 33 Distinct Values in Range 33 Range Utility Functions 34 FUNCTIONS IN KOTLIN 34 Built-in Functions in Kotlin 34 User-Defined Functions 34 Function Parameters 35 Return Values 35 Unit-Returning Functions 36 Recursive Function in Kotlin 36 Tail Recursion in Kotlin 37 Higher-Order Functions 38
📄 Page 9
viii ◾ Contents Lambda Function in Kotlin 38 Inline Function in Kotlin 38 If-else EXPRESSION IN KOTLIN 39 if Statement 39 if-else Statement 40 if-else Expression in Kotlin as the Ternary Operator 42 if-else-if Ladder Expression 42 nested if Expression 44 while loop IN KOTLIN 45 do-while loop IN KOTLIN 47 Method of do-while loop 47 for loop IN KOTLIN 48 Iterate across the Range Using a for loop 49 Using a for loop, Iterate over the Array 50 Iterate through a String Using the for loop 51 Iterate over the Collection Using the for loop 52 KOTLIN when expression 52 when to Use as a Statement with else 53 Using when as a Statement in the Absence of an else Branch 53 when Used as an Expression 53 In Kotlin, Different Ways to Use a when Block 54 UNLABELED BREAKS IN KOTLIN 57 In a while loop, Use of an Unlabeled Break 57 In a do-while loop, Use of an Unlabeled Break 58 Use of an Unlabeled Break in a for loop 59 LABELED BREAKS IN KOTLIN 60 In a while loop, Using a Labeled Break 60 In a do-while loop, Using a Labeled Break 61 Using a Labeled Break in a for loop 62 KOTLIN UNLABELED CONTINUE 63 Use of Unlabeled Continues in the while loop 63
📄 Page 10
Contents ◾ ix In a do-while loop, Use an Unlabeled Continue 64 Use of Unlabeled Continues in a for loop 64 KOTLIN LABELED CONTINUES 65 Use of Labeled Continues in a while loop 65 Use of Labeled Continues in a do-while loop 66 Use of Labeled Continues in a for loop 67 EXCEPTIONAL HANDLING 68 Exceptions in Kotlin 68 Exception Handling in Kotlin 69 Avoiding NullPointerException 70 What If We Fail to Deal with Exceptions? 70 How to Throw an Exception 70 KOTLIN try-catch block 71 The try-catch block as an Expression in Kotlin 72 The final block in Kotlin 72 Kotlin throw keyword 74 NESTED try block AND MULTIPLE catch block 74 Nested try block 74 Multiple catch block 75 NULL SAFETY 77 Nullable and Non-Nullable Sorts in Kotlin 77 Checking for the null in Conditions 78 Safe Call operator(?.) 79 Elvis Operator(?:) 80 Not null assertion: !! Operator 80 TYPE CHECKING AND SMART CASTING 81 Type Checking 81 Smart Casting 82 Use of !is Operator 83 EXPLICIT TYPE CASTING 83 Unsafe Cast Operator: as 84 Safe Cast Operator: as? 85
📄 Page 11
x ◾ Contents REGEX AND RANGES 85 Regular Expressions in Kotlin 85 Regex Functions 86 RANGES IN KOTLIN 89 (..) operator 90 rangeTo() Function 90 downTo() Function 91 Range Using the forEach loop 91 step() 92 reverse() Function 92 Various Predefined Functions in the Range 92 Chapter 2 ◾ OOP in Kotlin 95 OBJECTS AND CLASSES 95 Object-Oriented Programming Language 95 Class 96 Object 97 NESTED CLASS AND INNER CLASS IN KOTLIN 98 Nested Class 98 Inner Class in Kotlin 100 Inner-Class Kotlin Program 101 SETTERS AND GETTERS 102 Setters and Getters 103 Program of Default Setter and Getter in Kotlin 103 Identifiers for Values and Fields 104 Private Modifier 104 Setter and Getter with Custom Parameters 105 CLASS PROPERTIES AND CUSTOM ACCESSORS 106 Property 106 Customer Accessors 107 KOTLIN CONSTRUCTOR 108 Primary Constructor 108
📄 Page 12
Contents ◾ xi Primary Constructor with Initializer Block 109 The Default Value in the Primary Constructor 109 Secondary Constructor 110 VISIBILITY MODIFIERS IN KOTLIN 112 Public Modifier 112 Private Modifier 113 Internal Modifier 114 Protected Modifier 114 Overriding the Protected Modifier 115 Constructor Visibility 116 INTERFACES IN KOTLIN 116 Creating Interfaces 116 Implementing Interfaces 116 Default Methods and Default Values 117 Interface Properties 118 Interface Inheritance 119 Implementation of Multiple Interfaces 120 DATA CLASSES 121 Rules for Creating Data Classes 121 toString() 122 copy() 123 hashCode() and equals() 124 SEALED CLASSES 125 KOTLIN ABSTRACT CLASS 128 Multiple Derived Classes 130 INHERITANCE IN KOTLIN 131 Inheritance Use 132 Primary Constructor for an Inheritance 135 Secondary Constructor for an Inheritance 136 Overriding Member Functions and Attributes 137 Calling Superclass Implementation 138
📄 Page 13
xii ◾ Contents COMPOSITION 138 Substitution Principle of Liskov 139 Antipatterns of Implementation Inheritance 140 Inheritance of a Single Implementation 140 Tight Coupling 141 Unnecessary Exposure of Superclass APIs 141 Exploding Numbers of Subclasses 142 Composition Refactoring 143 UserMediator Class Is Being Refactored 143 From Composition to Aggregation 144 Handling the Exposure Issue 146 Composition over Inheritance 147 The Kotlin Method 147 ENCAPSULATION 149 POLYMORPHISM 150 ENCAPSULATION AND PROCEDURAL PROGRAMMING IN KOTLIN 152 Example of Procedural Programming 152 OOP 153 Tips for Choosing between Procedural and OOP 153 Procedural 154 OOP and Encapsulation 154 Putting Everything Together 154 Chapter 3 ◾ Usability Aspects of Kotlin 157 NULL SAFETY IN KOTLIN 157 Nullable and Non-Nullable Types in Kotlin 158 Nullable Types 158 Non-Nullable Types 158 Checking for Null in the Conditions 159 SMART CAST 159 Use of is for the Smart Cast 160 Use of !is for the Smart Cast 160
📄 Page 14
Contents ◾ xiii UNSAFE AND SAFE CAST OPERATOR 160 Unsafe Cast Operator: as 160 Safe Cast Operator: as? 161 (?:) Elvis Operator 162 EXTENSION FUNCTION 164 Extended Library Class Using an Extension Function 165 Extensions Are Resolved Statically 165 Nullable Receiver 166 Companion Object Extensions 167 OVERLOADING OF THE OPERATOR IN KOTLIN 168 Unary Operators 168 Increment and Decrement Operators 169 Binary Operators 170 Other Operators 171 Enum CLASSES IN KOTLIN 171 Enum Initializing 172 Enum Properties and Methods 173 Properties and Functions of the Enum Class 174 Enums as Anonymous Classes 175 Usage of when Expression with the Enum Class 175 KOTLIN GENERICS 176 Generic Usage in Our Program 177 Variance 178 The out Keyword 178 The in Keyword 179 Covariance 179 Contra Covariance 180 Type Projections 180 Star Projections 181 Chapter 4 ◾ Kotlin Functional Programming 183 LAMBDA EXPRESSIONS AND ANONYMOUS FUNCTIONS IN KOTLIN 183
📄 Page 15
xiv ◾ Contents LAMBDA EXPRESSION 184 Inference in Lambda Types 185 Type Declaration in Lambdas 185 it: Implicit Name of a Single-Parameter 186 Returning a Value from a Lambda Expression 187 ANONYMOUS FUNCTION 187 Return Type and Parameters 188 The Distinction between Lambda Expressions and Anonymous Functions 188 HIGHER-ORDER FUNCTIONS IN KOTLIN 188 Higher-Order Function 189 Returning a Function from a Higher-Order Function 192 KOTLIN LOCAL FUNCTIONS 193 SCOPE FUNCTION IN KOTLIN 196 SCOPE FUNCTIONS 197 Utilization of Scope Functions 197 Scope Function Types 198 Object References 202 Return Values 203 KOTLIN COLLECTIONS 204 Types of Collections 204 Immutable Collection 204 Mutable Collection 206 ArrayList IN KOTLIN 207 listOf() IN KOTLIN 211 Indexing List Elements in Kotlin 212 The First and Last Elements 212 Iteration Methods for Lists 213 Sorting the List’s Elements 214 The Functions contains() and containsAll() 215 setOf() in Kotlin 216 Set Indexing 217
📄 Page 16
Contents ◾ xv Set Basics 217 The Functions contains() and containsAll() 218 mutableSetOf() METHOD IN KOTLIN 219 Set Indexing 220 Set the First and Last Element 221 Traversal in a mutableSet 221 The Methods contains() and containsAll() 221 hashSetOf() IN KOTLIN 222 hashSet Traversal 224 Indexing in a hashSet 224 The Functions contains() and containsAll() 224 mapOf () in Kotlin 225 Map Size 226 Empty Map 226 Get Map Values 227 Map Contains Keys or Values 227 Two Values and the Same Key 228 HashMap IN KOTLIN 228 HashMap Functions Use 229 HashMap Time Complexity 232 Chapter 5 ◾ Code Management and Exception Handling 233 EXCEPTIONAL HANDLING | TRY, CATCH, THROW, AND FINALLY 233 Exceptions in Kotlin 234 Exception Handling 234 What If We Don’t Deal with Exceptions? 235 How to Throw an Exception in Kotlin 235 NullPointerException Example 236 How to Avoid NullPointerException 236 KOTLIN try-catch block 237 Kotlin try-catch block as an Expression 237
📄 Page 17
xvi ◾ Contents Kotlin Finally Block 238 Kotlin throw Keyword 239 NESTED try block AND MULTIPLE catch block 240 Nested try block 240 Multiple catch block 241 LOGGING IN KOTLIN 243 The Easiest Kotlin Logging That Could Work 243 What Is Application Logging? 244 Using Logback for Kotlin Logging 244 Add Logback to Our Project 244 Calling LogBack from Kotlin 245 Why Log? 246 What Logging Method Should We Use? 246 Configuring Logger 247 Formatting Kotlin Logging Messages 248 Logging to a File 249 Setting Kotlin Logging Levels 249 UNIT TESTING 251 Simple Android Application 251 Project Setup 251 Our First Test 251 Test Structure 252 Given Block 252 When Block 253 Then Block 253 Running Test 254 NOTHING BY KOTLIN: ITS APPLICABILITY IN GENERICS 254 Key Points 256 Chapter 6 ◾ Code Optimization Ideas 257 OPTIMIZATION TIPS 257 Using Static Layout Imports in Kotlin 257
📄 Page 18
Contents ◾ xvii Creating POJO Classes in Kotlin 259 Constructors and Inheritance in Kotlin 261 Using Lambda Functions in Kotlin 262 Tail Recursion, Sealed Classes, Local, Infix, Inline Functions, and More Advanced Kotlin Tips 263 Local Functions 263 Infix Functions 263 Inline Functions 263 Tail Recursion 264 Sealed Classes 264 Some More Helpful Tips 265 Local Return 265 Operator Overloading 266 Lambda Extensions 266 lateinit 267 Companion Objects 267 Tips for Improving Kotlin Compilation Times 267 General Suggestions 267 Configuration of Gradle 268 Configuration of Windows 269 WRITING SECURE CODE 269 Set Up Source Code and Tests in Our Android Apps 270 How Does Kotlin Code Look? 270 Why Is It Superior to Java? 270 Adapting an Existing Android Project to Utilize Kotlin 270 Existing Java Files Can Convert to Kotlin 272 Writing Tests in the Kotlin 273 BEST CODING PRACTICES 275 Accept Immutability 275 Get Rid of ArrayList and HashMap 276 Make Use of Functional Constructs 276 javaClass 278
📄 Page 19
xviii ◾ Contents String Interpolation 278 Infer Types 279 Semantic Test Naming 280 Safe Operator? 280 Elvis Throws 281 List Literals in Annotations 281 Collection Helpers 282 No more .equals() 283 Method Readability – Named Parameters 284 HOW KOTLIN OUTPERFORMS JAVA IN SOLVING LONG-STANDING SECURITY ISSUES 285 Typing, Syntax, and Speed Compared 285 Null Reference Exceptions Pose Security Risks 286 Kotlin Has Everything That Java Needs 287 Finally, There Is More to It Than Simply Null 288 WHAT EXACTLY IS APPLICATION HARDENING? 289 What Is the Purpose of Application Hardening? 289 Is Our Application in Need of Hardening? 289 Application Hardening Methods 290 Benefits of Application Hardening 291 Application Patches 291 Chapter 7 ◾ Kotlin for Android Development 293 BUILDING ANDROID Apps IN KOTLIN 293 Download and Install Android Studio 294 Create Our First Project 295 EXPLORE LAYOUT EDITOR 298 ADD COLOR RESOURCES 303 ADD VIEWS AND CONSTRAINTS 305 CHANGE THE LOOK OF THE BUTTONS AND THE TextView 313 BENEFITS OF KOTLIN FOR ANDROID App DEVELOPMENT 314 The Benefits of Kotlin-Based Android App Development 314
📄 Page 20
Contents ◾ xix INTEGRATE in-app REVIEWS 316 Set Up Our Development Environment 316 Create ReviewManager 316 Request ReviewInfo Object 316 Launch in-app Review Flow 317 APPRAISAL, 319 CHEAT SHEET, 337 BIBLIOGRAPHY, 357 INDEX, 363
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List