Share E-Book

Kotlin Mastery A Comprehensive Guide for Java Developers and New Programmers (Arnika Patel, Keshav Kumar etc.)(Z-Library)

Author

,
,

Rating No ratings yet

Log in to rate

Java
Language English

Enhance your programming toolkit and build robust applications by mastering Kotlin. This book connects Java and Kotlin through side-by-side code samples and practical demonstrations. Java programmers and up-and-coming developers seeking to learn Kotlin need to do so with confidence. Starting with the fundamentals of basic syntax, this book will cover data types, variables, control flow statements. From there move on to advanced topics like object-oriented programming concepts with null safety, lambdas, functions, inheritance and coroutines. Additionally, you’ll delve into practical applications such as designing custom domain-specific languages, working with Kotlin Multiplatform, and leveraging reactive extensions. With numerous hands-on exercises and real-world examples, you'll gain the expertise needed to explore advanced projects. What You Will Learn Explore object-oriented and functional programming with Kotlin to create modular code. Review Kotlin’s techniques for error handling and exception management. Implement Kotlin coroutines for efficient concurrency and asynchronous task management. Design custom domain-specific languages and use the Kotlin standard library for string manipulation and file handling. Who This Book is For Java developers and programmers looking to master Kotlin.

Format PDF
Size 9.0 MB
8
Views
(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
Kotlin Mastery A Comprehensive Guide for Java Developers and New Programmers — Arnika Patel Keshav Kumar Dr. Bishwajeet Pandey
Page 2
Kotlin Mastery A Comprehensive Guide for Java Developers and New Programmers Arnika Patel Keshav Kumar Dr. Bishwajeet Kumar Pandey
Page 3
Kotlin Mastery: A Comprehensive Guide for Java Developers and New Programmers ISBN-13 (pbk): 979-8-8688-1617-8 ISBN-13 (electronic): 979-8-8688-1618-5 https://doi.org/10.1007/979-8-8688-1618-5 Copyright © 2025 by Arnika Patel, Keshav Kumar, and Dr. Bishwajeet Kumar Pandey This work is subject to copyright. All rights are reserved by the publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Melissa Duffy Development Editor: James Markham Editorial Assistant: Gryffin Winkler Copy Editor: April Rondeau Cover designed by eStudioCalamar Cover image designed by Milad Fakurian on Unsplash Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/services/ source-code. If disposing of this product, please recycle the paper Arnika Patel Paul University, Vadodara, Gujarat, India Keshav Kumar Kanpur, Uttar Pradesh, India Dr. Bishwajeet Kumar Pandey GL Bajaj Institute of Technology and Management, Greater Noida West, Uttar Pradesh, India
Page 4
iii Table of Contents About the Authors xiii About the Technical Reviewer xv Chapter 1: Introduction to Kotlin 1 1.1 Kotlin vs. Java ......................................................................................................................... 1 1.2 Features of Kotlin .................................................................................................................... 4 1.3 Benefits and Drawbacks of Kotlin ........................................................................................... 6 Benefits ................................................................................................................................... 6 Drawbacks ............................................................................................................................... 7 1.4 Applications of Kotlin .............................................................................................................. 7 1.5 Setting Up Your Development Environment ............................................................................ 8 For Command Line .................................................................................................................. 8 Running Kotlin Commands in the Command Line ................................................................... 9 Development Environment for IntelliJ IDEA ........................................................................... 13 Creating Your First Application in Kotlin ................................................................................ 15 1.6 Summary............................................................................................................................... 18 1.7 Test Your Knowledge ............................................................................................................. 18 1.8 Answers ................................................................................................................................ 21 Chapter 2: Fundamentals of Kotlin Programming 23 2.1 Basic Structure and Syntax ................................................................................................... 23 Kotlin Output .......................................................................................................................... 24 2.2 Using Comments in Kotlin ..................................................................................................... 25 Single-Line Comments .......................................................................................................... 25 Multi-Line Comments ............................................................................................................ 25 2.3 Variables ............................................................................................................................... 26
Page 5
iv 2.4 Datatypes .............................................................................................................................. 26 2.5 Operators .............................................................................................................................. 27 Arithmetic Operators ............................................................................................................. 27 Logical Operators .................................................................................................................. 29 Assignment Operators ........................................................................................................... 30 Comparison Operators ........................................................................................................... 31 2.6 Kotlin Strings ........................................................................................................................ 32 String Length ......................................................................................................................... 33 String Functions .................................................................................................................... 33 2.7 Kotlin Arrays .......................................................................................................................... 34 Array Length .......................................................................................................................... 35 Array Element Change ........................................................................................................... 35 Checking If an Item Exists ..................................................................................................... 36 Accessing Array Items Using Loop ........................................................................................ 36 2.8 Control Flow .......................................................................................................................... 37 if ............................................................................................................................................ 37 else ........................................................................................................................................ 38 else if ..................................................................................................................................... 39 when ...................................................................................................................................... 40 2.9 Loops .................................................................................................................................... 41 while ...................................................................................................................................... 41 do..while ................................................................................................................................ 42 for .......................................................................................................................................... 43 2.10 Return and Jumps ............................................................................................................... 43 break ..................................................................................................................................... 43 continue ................................................................................................................................. 44 return ..................................................................................................................................... 45 2.11 Type Checks ........................................................................................................................ 45 2.12 Smart Cast .......................................................................................................................... 46 Table of ConTenTs
Page 6
v 2.13 Real-Life Programming Practices ....................................................................................... 46 2.14 Summary............................................................................................................................. 49 2.15 Test Your Knowledge ........................................................................................................... 49 2.16 Answers .............................................................................................................................. 52 Chapter 3: Functions in Kotlin 53 3.1 A Closer Look ........................................................................................................................ 53 User-Defined Functions ......................................................................................................... 53 Parameters in Functions........................................................................................................ 54 Body of Functions .................................................................................................................. 54 Return Value of the Functions ............................................................................................... 54 Calling Functions ................................................................................................................... 55 Standard Library Functions ................................................................................................... 56 Advantages and Disadvantages of Using Functions in Kotlin ................................................ 57 3.2 Functions with Default and Named Arguments .................................................................... 58 Default Arguments ................................................................................................................. 58 Named Arguments ................................................................................................................. 60 3.3 Recursive Functions .............................................................................................................. 61 Normal Function Call ............................................................................................................. 61 Recursive Function Call ......................................................................................................... 63 3.4 Tail Recursive Functions ....................................................................................................... 64 3.5 Programming Practices ........................................................................................................ 65 3.6 Summary............................................................................................................................... 68 3.7 Test Your Knowledge ............................................................................................................. 69 3.8 Answers ................................................................................................................................ 71 Chapter 4: Object-Oriented Programming with Kotlin 73 4.1 Classes and Objects .............................................................................................................. 74 Classes .................................................................................................................................. 74 Objects .................................................................................................................................. 75 Nested Classes ...................................................................................................................... 78 Inner Classes ......................................................................................................................... 79 Table of ConTenTs
Page 7
vi 4.2 Constructors .......................................................................................................................... 80 Primary Constructor .............................................................................................................. 81 Using Secondary Constructors .............................................................................................. 84 4.3 Inheritance ............................................................................................................................ 86 Kotlin Override Property ........................................................................................................ 87 Kotlin Inheritance with Primary Constructor ......................................................................... 88 Kotlin Inheritance with Secondary Constructor ..................................................................... 89 Calling Base Class Secondary Constructor from Derived Class Secondary Constructor ....... 90 4.4 Interfaces .............................................................................................................................. 91 Default Values and Methods .................................................................................................. 92 Properties in Interfaces ......................................................................................................... 93 Inheritance in Interfaces ........................................................................................................ 94 Multiple Interfaces ................................................................................................................. 95 4.5 Visibility Modifiers ................................................................................................................. 96 4.6 Property ................................................................................................................................ 99 Class Properties..................................................................................................................... 99 Setters and Getters .............................................................................................................. 100 Access Getter and Setter ..................................................................................................... 101 Custom Setter and Getter .................................................................................................... 101 4.7 Abstract Class ..................................................................................................................... 102 Overriding Non-abstract Open Member with the Abstract .................................................. 103 Multiple Derived Classes ..................................................................................................... 104 4.8 Data Class ........................................................................................................................... 105 4.9 Sealed Class ....................................................................................................................... 107 4.10 Enum Class ....................................................................................................................... 108 Enum Properties and Methods ............................................................................................ 109 4.11 Practical Programming Exercises ..................................................................................... 111 4.12 Summary........................................................................................................................... 124 4.13 Test Your Knowledge ......................................................................................................... 124 4.14 Answers ............................................................................................................................ 126 Table of ConTenTs
Page 8
vii Chapter 5: Error Handling and Exceptions 127 5.1 Exception-Handling Basics ................................................................................................. 127 The try-catch Block as an Expression ................................................................................. 129 Finally Block ........................................................................................................................ 130 Throw Keyword.................................................................................................................... 132 5.2 Nested try Block .................................................................................................................. 133 Multiple Catch Blocks .......................................................................................................... 134 Using When in Catch Block .................................................................................................. 136 5.3 Custom Exceptions ............................................................................................................. 137 5.4 Real-Life Programming Practices ....................................................................................... 138 5.5 Summary............................................................................................................................. 143 5.6 Test Your Knowledge ........................................................................................................... 143 5.7 Answers .............................................................................................................................. 145 Chapter 6: Collections and Generics 147 6.1 Collections .......................................................................................................................... 147 6.2 List ...................................................................................................................................... 148 6.3 Set ....................................................................................................................................... 153 6.4 Maps ................................................................................................................................... 158 6.5 Generics .............................................................................................................................. 164 Basics of Generics ............................................................................................................... 164 6.6 Real-Life Programming Practices ....................................................................................... 170 6.7 Summary............................................................................................................................. 172 6.8 Test Your Knowledge ........................................................................................................... 172 6.9 Answers .............................................................................................................................. 175 Chapter 7: Kotlin Coroutines 177 7.1 Introduction ......................................................................................................................... 177 7.2 Creating Coroutines ............................................................................................................ 177 7.3 Structured Concurrency ...................................................................................................... 178 7.4 Extract Function Refactoring............................................................................................... 179 Table of ConTenTs
Page 9
viii 7.5 Scope Builder and Concurrency .......................................................................................... 179 Scope Builder ...................................................................................................................... 179 Concurrency ........................................................................................................................ 180 7.6 An Explicit Job ..................................................................................................................... 181 7.7 Coroutines Are Lightweight ................................................................................................. 182 7.8 Coroutine Exception Handling ............................................................................................. 182 7.9 Coroutine Exception Handler ............................................................................................... 183 7.10 Cancellation and Exceptions ............................................................................................. 184 7.11 Exception Aggregation ...................................................................................................... 185 7.12 Real-Life Programming Practices ..................................................................................... 186 7.13 Summary........................................................................................................................... 188 7.14 Test Your Knowledge ......................................................................................................... 188 7.15 Answers ............................................................................................................................ 191 Chapter 8: Kotlin Domain-Specific Language (DSL) 193 8.1 Introduction to Kotlin DSLs ................................................................................................. 193 Advantages of DSLs ............................................................................................................. 193 8.2 Writing Our First DSL ........................................................................................................... 194 8.3 DSL by Applying Builder Pattern ......................................................................................... 197 8.4 DSL with Collections ........................................................................................................... 198 8.5 DSL with @DslMarker Annotation ....................................................................................... 201 8.6 Real-Life Programming Practices ....................................................................................... 202 8.7 Summary............................................................................................................................. 208 8.8 Test Your Knowledge ........................................................................................................... 208 8.9 Answers .............................................................................................................................. 212 Chapter 9: Kotlin Standard Library 213 9.1 Introduction to the Kotlin Standard Library ......................................................................... 213 9.2 Collection Functions ............................................................................................................ 213 Sorting ................................................................................................................................. 213 9.3 String Functions .................................................................................................................. 220 Table of ConTenTs
Page 10
ix 9.4 Extension Functions ............................................................................................................ 224 Extended Library Classes .................................................................................................... 225 9.5 Null Safety Functions .......................................................................................................... 225 9.6 File and I/O Functions ......................................................................................................... 226 Create File ........................................................................................................................... 226 Writing to File ...................................................................................................................... 226 Reading from File ................................................................................................................ 226 Delete File ............................................................................................................................ 227 9.7 Real-Life Programming Practices ....................................................................................... 227 9.8 Summary............................................................................................................................. 229 9.9 Test Your Knowledge ........................................................................................................... 229 9.10 Answers ............................................................................................................................ 233 Chapter 10: Testing in Kotlin 235 10.1 Unit Testing ....................................................................................................................... 235 The Significance of Unit Testing .......................................................................................... 235 Establishing the Testing Environment.................................................................................. 236 Composing Your Initial Unit Test .......................................................................................... 236 Optimal Strategies for Unit Testing ...................................................................................... 239 Testing Frameworks ............................................................................................................ 241 10.2 Kotlin Unit Testing with MockK ......................................................................................... 242 Mocking and MockK: mocking in kotlin behaves like external real dependencies and mockK is powerful and lightweight mocking library ............................. 243 MockK Annotations .............................................................................................................. 243 MockK Keywords ................................................................................................................. 245 10.3 Kotlin Integration Testing .................................................................................................. 245 Integration Testing in Kotlin with Ktor ................................................................................. 248 10.4 Conclusion ........................................................................................................................ 248 10.5 Test Your Knowledge ......................................................................................................... 250 10.6 Answers ............................................................................................................................ 253 Table of ConTenTs
Page 11
x Chapter 11: Kotlin Reactive Extension 255 11.1 Introduction to RxKotlin..................................................................................................... 255 11.2 Core Rx Concepts .............................................................................................................. 256 Streams: The Heart of Reactive Programming .................................................................... 257 Hot and Cold Observables ................................................................................................... 257 Flow of Hot and Cold Streams ............................................................................................. 257 11.3 Usage of Rx ....................................................................................................................... 258 Basic RxKotlin Usage ........................................................................................................... 258 Using filter and distinct ....................................................................................................... 259 Observable.Interval for Periodic Emissions ......................................................................... 260 11.4 Kotlin Coroutines ............................................................................................................... 261 11.5 Reactive Programming Patterns ....................................................................................... 262 11.6 Best Practices for Testing Reactive Code .......................................................................... 263 11.7 Conclusion ........................................................................................................................ 264 11.8 Real-Life Programming Practices ..................................................................................... 264 11.9 Test Your Knowledge ......................................................................................................... 266 11.10 Answers .......................................................................................................................... 268 Chapter 12: Working with API and Networking 269 12.1 Introduction to Kotlin APIs ................................................................................................. 269 12.2 Android Development APIs ................................................................................................ 270 12.3 Networking APIs ................................................................................................................ 272 12.4 Database & Storage APIs .................................................................................................. 272 12.5 UI & Graphics APIs ............................................................................................................. 273 12.6 Machine Learning & IoT APIs ............................................................................................ 273 12.7 Multimedia APIs ................................................................................................................ 274 12.8 Cloud & Backend APIs ....................................................................................................... 275 12.9 CASE STUDY 1: Using Google Map API in Kotlin ................................................................ 275 STEP 1. Enable Google Maps API ......................................................................................... 275 STEP 2. Add Dependencies .................................................................................................. 276 STEP 3. Add API Key to Manifest ......................................................................................... 276 Table of ConTenTs
Page 12
xi STEP 4. Add a Map Fragment .............................................................................................. 276 STEP 5. Load the Map in Kotlin ........................................................................................... 277 STEP 6. Run the App ............................................................................................................ 278 Extra Features ..................................................................................................................... 278 12.10 CASE STUDY 2: Using MQTT API in Kotlin ........................................................................ 278 STEP 1. Create a New Kotlin Project in IntelliJ IDEA ........................................................... 278 STEP 2. Add MQTT Dependency .......................................................................................... 279 STEP 3. Implement MQTT Client in Kotlin ............................................................................ 279 STEP 4. Run the MQTT Client ............................................................................................... 281 STEP 5. Explanation ............................................................................................................. 281 STEP 6. Extra Features ........................................................................................................ 281 12.11 Conclusion and Future Scope ......................................................................................... 281 12.12 Test Your Knowledge ....................................................................................................... 282 12.13 Answers .......................................................................................................................... 284 Chapter 13: Advanced Kotlin Programming 285 13.1 Introduction ....................................................................................................................... 285 13.2 Null Safety ......................................................................................................................... 286 Safe Call Operator in Kotlin ................................................................................................. 287 Elvis Operator in Kotlin ........................................................................................................ 288 Non-Null Assertion (!!) in Kotlin ........................................................................................... 290 Safe Cast (as?) .................................................................................................................... 291 let Scope Function ............................................................................................................... 292 13.3 Higher-Order Functions and Lambdas .............................................................................. 294 Higher-Order Function with Lambda ................................................................................... 294 Higher-Order Function Returns a Function .......................................................................... 296 Using Lambda with List Functions ...................................................................................... 297 13.4 Lazy Initialization .............................................................................................................. 299 13.5 Property Delegation .......................................................................................................... 300 13.6 Conclusion ........................................................................................................................ 302 13.7 Future Scope ..................................................................................................................... 302 Table of ConTenTs
Page 13
xii 13.8 Real-Life Programming Practice ....................................................................................... 303 13.9 Test Your Knowledge ......................................................................................................... 306 13.10 Answers .......................................................................................................................... 309 Chapter 14: Data Analysis with Kotlin 311 14.1 Get Started with Kotlin Notebook ...................................................................................... 311 14.2 Add Library to Kotlin Notebook ......................................................................................... 315 14.3 Working with Data Sources ............................................................................................... 316 14.4 Data Visualization in Kotlin Notebook with Kandy ............................................................. 320 Create Line Chart ................................................................................................................. 320 Create Points Chart .............................................................................................................. 322 Create Bar Chart .................................................................................................................. 323 14.5 Libraries for Data Analysis in Kotlin .................................................................................. 325 14.6 Real-Life Programming Practice ....................................................................................... 325 14.7 Summary........................................................................................................................... 327 14.8 Test Your Knowledge ......................................................................................................... 327 14.9 Answers ............................................................................................................................ 330 Chapter 15: Kotlin Multiplatform 333 15.1 Introduction to Kotlin Multiplatform .................................................................................. 333 How It Works ....................................................................................................................... 334 Benefits of KMP ................................................................................................................... 335 Use Cases ............................................................................................................................ 335 15.2 Setting Up a Multiplatform Project for iOS ........................................................................ 336 Steps for Creating iOS Project ............................................................................................. 338 Shared Module Configuration and Implementation ............................................................. 339 15.3 Multiplatform Libraries ..................................................................................................... 340 Dependency on a Kotlin Library ........................................................................................... 341 Dependency on Another Multiplatform Project .................................................................... 342 15.4 Test Your Knowledge ......................................................................................................... 343 15.5 Answers ............................................................................................................................ 345 Index 347 Table of ConTenTs
Page 14
xiii About the Authors Arnika Patel currently serves as assistant professor at Parul University, Vadodara, Gujarat, where she continues to inspire and educate future tech innovators. She was a Kotlin developer with over six months’ experience in the tech industry, which was in addition to more than two and a half years as an assistant professor. Holding a master’s degree in engineering, her expertise in both software development and academia is well established. In 2015, she was honored with the prestigious Devang Mehta IT Award, a testament to her contributions to the field. She is also a proud member of the Indian Society for Technical Education (ISTE), reflecting her commitment to advancing the field of engineering education. Her blend of practical experience and academic insight informs her writing, offering valuable perspectives for both technology enthusiasts and professionals. Her area of specialization includes mobile ad-hoc networks, artificial intelligence, machine learning, and so forth. Keshav Kumar is an assistant professor at the Department of Electronics and Communication Engineering at the Pranveer Singh Institute of Technology, Kanpur, India. His areas of specialization include deep learning, hardware security, green communication, low-power VLSI design, machine learning techniques, Wireless Sensor Networks (WSN), and Internet of Things (IoT). He has experience teaching Python programming, embedded systems, IoT, computer networks, and digital electronics.
Page 15
xiv Dr. Bishwajeet Kumar Pandey is a professor at GL Bajaj College of Technology and Management, Greater Noida, India. He has been a senior member of IEEE since 2019. He has over 15 years of industry and teaching experience and has authored and co-authored more than 170 papers. He has experience teaching ethical hacking, application and web security, cloud migration, incident handling and response, information security, artificial intelligence, machine learning, computer networks, and digital logic. abouT The auThors
Page 16
xv Siddharth Kumar Patel has experience in successfully building and deploying a production Android application using current technologies like Kotlin and Jetpack Compose. He also has a solid Java background and extensive experience in Agile methodologies, which positions him as a good Android developer. His proficiency in developing data-intensive, responsive applications and his skill set with relevant industry tools further underscores his suitability. His proactive approach to continuous learning, evidenced by completing Google-designed learning pathways, indicates a dedication to staying current with evolving Android best practices. About the Technical Reviewer
Page 17
1 © Arnika Patel, Keshav Kumar, and Dr. Bishwajeet Kumar Pandey 2025 A. Patel et al., Kotlin Mastery, https://doi.org/10.1007/979-8-8688-1618-5_1 CHAPTER 1 Introduction to Kotlin Kotlin is an object-oriented programming language developed by Jetbrains in 2016. Sponsored by Google, and one of the official languages for Android, Kotlin has become very popular because of its compatibility with Java and different platforms, such as Windows, Mac, Linux, and Raspberry Pi. In this chapter we’ll get you grounded with some basics and close by setting up your development environment. 1.1 Kotlin vs. Java Kotlin and Java are both good programming languages, and both are object-oriented programming languages, though developed for different reasons. Kotlin is mainly used for Android application development, whereas Java is mainly used for enterprise application development. Java, a very popular programming language, was developed in 1996. Over the years it has developed quite a large community, but Kotlin is a new programming language with some modern features, making it an attraction for developers. One of the most important differences between Kotlin and Java is syntax. Kotlin has very concise syntax as compared to Java, so one needs to write less code than when using Java. Also, Kotlin is more readable than Java. In Kotlin there is no need to define datatypes, as the compiler will automatically define them according to the values assigned. In Java there is the possibility of any variable facing a null value, which can result in null pointer exceptions at runtime. Kotlin differs here, as in Kotlin you can decide whether the variable can be null or not. Thus you can avoid null pointer exceptions, which are very common in Java. Kotlin uses extension functions, which means we can use any function of a class without creating a new class and inheriting it. In Java, to use the functionality of one class you need to create other class and inherit the class whose functionality you want to use.
Page 18
2 In Android, one component that belongs to one application runs in the same process and same thread, which is the main thread and is responsible for the user interface (UI). Network operations and CPU operations are very lengthy, resulting in slow performance. To avoid this type of blockage, Java uses multithreading, where all of these operations run on multiple threads, making it more complex to handle. Kotlin uses coroutines, which is more clear and concise than handling multiple threads. In Java there is a need to create fields or variables to store the data, constructors, and getter and setter for variables or fields, in addition to other functions like toString(), equals(), and so on. These classes are mainly intended to store data rather than having any functionality. Meanwhile, Kotlin provides a very simple way to create data classes— give keyword data as a prefix of the class name, and the compiler will automatically generate all the getters and setters for variables, and also constructors. Kotlin uses a smart cast feature, which means the compiler will automatically handle redundant casts using the is-checks keyword. But in Java, the developer must check a variable’s type in compatibility operations. In Java there is checked exception support, so there must be a catch statement and exception declaration as needed. This ensures robust code, because errors are handled by checked exceptions. But it can be time consuming. Kotlin doesn’t have checked exception support, meaning no declaration of exceptions or catch is required. Kotlin is a mix of object-oriented and functional programming languages. Functional programming handles computational or mathematical functions. Higher-order functions and lambdas are examples of functional programming concepts present in Kotlin. Whereas Java is purely an object-oriented programming language, Java 8 has lambda functions. Kotlin does not have wildcards ( ?- question mark -unknown type of variable), ternary operators, and public fields. Java does have wildcards, ternary operators, and public fields. Table 1-1 shows the pointed differences between Java and Kotlin. Chapter 1 IntroduCtIon to KotlIn
Page 19
3 Table 1-1. Kotlin vs. Java Kotlin Java type object-oriented and functional programming language purely object-oriented programming language First stable version released on 15 February 2016 23 January 1996 product of Jetbrains oracle Community Support as it is new technology, smaller community than Java large Community of developers use used for mobile application development and server-side applications used for enterprise applications, desktop applications, mobile applications extensions .kt (kotlin source file) .kts (kotlin script file) .ktm (kotlin module) .java (java source file) .class (class file) .jar (archived file) line of Code (loC) less as compared to Java More as compared to Kotlin datatype no need to assign, compiler will automatically assign datatype to variable Compulsory to assign datatype to variable null Safety available not available extension Function We can create extension functions not supported by Java Coroutine We can create multiple threads in Kotlin by using coroutines In Java, coroutines are not available; we need to use multithreading for creating multiple threads, which is more complex data Class We can create data class in kotlin by giving prefix “data” We cannot create data classes in Java Smart Casts Supported not Supported Checked exception not available available (continued) Chapter 1 IntroduCtIon to KotlIn
Page 20
4 Table 1-1. (continued) Kotlin Java lambdas and higher- order Functions available in Kotlin available after Java 8 version Wildcards not available available public Fields not available available ternary operator not available available 1.2 Features of Kotlin Kotlin provides many features that make it very popular among developers. The following list shows each and every feature of Kotlin: • Interoperability: Kotlin is designed in such a way that it can be interoperable with Java. That means Java code can be called from Kotlin and Kotlin code can be called from Java. This allows all developers to smoothly migrate from Java to Kotlin or to use existing Java libraries in Kotlin code. • Concise: In Kotlin when you declare a variable there is no need to give the datatype, as the Kotlin compiler will automatically decide it. This and other functionalities, like null safety, extension functions, and so forth, are decided by Kotlin, thus reducing the amount of code required, as compared to Java. • Null Safety: In Java most developers face a common exception known as a null pointer exception, which can be very distressing. In Kotlin, the developer can mostly eliminate null pointer exceptions by using a null safety feature to decide whether the variable can be null or not. • Data Classes: Data classes are generally used for storing data. In Java the developer needs to declare the variable, getter, setter, and constructors, but in Kotlin the developer just needs to create one class by giving the prefix data before the class name, which will automatically create constructors, getter, and setter for the given variables. Chapter 1 IntroduCtIon to KotlIn
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List