Kotlin: The Ultimate Guide

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

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.

Author(s): Sufyan bin Uzayr
Publisher: CRC Press
Year: 2022

Language: English
Pages: 396
City: Boca Raton

Cover
Half Title
Title Page
Copyright Page
Contents
Acknowledgments
About the Author
CHAPTER 1: Crash Course in Kotlin
KOTLIN PROGRAMMING LANGUAGE HAS A RICH HISTORY
FEATURES OF THE KOTLIN PROGRAMMING LANGUAGE
KOTLIN PROGRAMMING LANGUAGE APPLICATIONS
WHY SHOULD WE STUDY THE KOTLIN PROGRAMMING LANGUAGE? WHAT ARE THE BENEFITS OF LEARNING THE KOTLIN PROGRAMMING LANGUAGE?
DISADVANTAGES OF KOTLIN
WHAT IS THE PURPOSE OF KOTLIN?
Android Development
Back-End Web Development
Full-Stack Web Development
Data Science
Mobile Development for Several Platforms
KOTLIN’S ARCHITECTURE
KOTLIN FRAMEWORKS FOR SERVER-SIDE DEVELOPMENT
KOTLIN ENVIRONMENT FOR COMMAND LINE SETUP
Intellij IDEA IS USED TO BUILD UP A KOTLIN ENVIRONMENT
THE FIRST PROGRAM IS WRITTEN IN KOTLIN
KOTLIN DATA TYPES
Number Data Types in Kotlin
Character Data Type in Kotlin
String Data Type in Kotlin
Boolean Data Type in Kotlin
Array Data Type in Kotlin
DATA TYPE CONVERSION IN KOTLIN
OPERATORS IN KOTLIN
Arithmetic Operators in Kotlin
Relational Operators in Kotlin
Assignment Operators in Kotlin
Unary Operators in Kotlin
Logical Operators in Kotlin
Bitwise Operations in Kotlin
BOOLEANS IN KOTLIN
Create Boolean Variables
Boolean Operators in Kotlin
Boolean Expression in Kotlin
and() and or() Functions in Kotlin
Boolean to String
STRINGS IN KOTLIN
String Templates in Kotlin
String Object in Kotlin
String Indexes in Kotlin
String Length in Kotlin
String Kotlin Last Index
String Case Changing
String Concatenation in Kotlin
Trim Characters from the String
Quotes Inside a String
Finding a String Inside a String
Comparing Two Strings
getOrNull() Function in Kotlin
toString() Function in Kotlin
ARRAYS IN KOTLIN
Creating Arrays
Arrays of the Primitive Type
Elements of an Array Can Be Get and Set
Array Length in Kotlin
Loop through an Array
Check if an Element Exists
Distinct Values from the Array
Dropping Elements from the Array
Checking an Empty Array
RANGES IN KOTLIN
Creating Ranges Using the rangeTo() Function
Creating the Ranges Using the .. Operator
Creating the Ranges Using downTo() Operator
step() Function in Kotlin
Range of Characters in Kotlin
reversed() Function in Kotlin
until() Function in Kotlin
The last, first, and step Elements
Filtering Ranges
Distinct Values in Range
Range Utility Functions
FUNCTIONS IN KOTLIN
Built-in Functions in Kotlin
User-Defined Functions
Function Parameters
Return Values
Unit-Returning Functions
Recursive Function in Kotlin
Tail Recursion in Kotlin
Higher-Order Functions
Lambda Function in Kotlin
Inline Function in Kotlin
If-else EXPRESSION IN KOTLIN
if Statement
if-else Statement
if-else Expression in Kotlin as the Ternary Operator
if-else-if Ladder Expression
nested if Expression
while loop IN KOTLIN
do-while loop IN KOTLIN
Method of do-while loop
for loop IN KOTLIN
Iterate across the Range Using a for loop
Using a for loop, Iterate over the Array
Iterate through a String Using the for loop
Iterate over the Collection Using the for loop
KOTLIN when expression
when to Use as a Statement with else
Using when as a Statement in the Absence of an else Branch
when Used as an Expression
In Kotlin, Different Ways to Use a when Block
UNLABELED BREAKS IN KOTLIN
In a while loop, Use of an Unlabeled Break
In a do-while loop, Use of an Unlabeled Break
Use of an Unlabeled Break in a for loop
LABELED BREAKS IN KOTLIN
In a while loop, Using a Labeled Break
In a do-while loop, Using a Labeled Break
Using a Labeled Break in a for loop
KOTLIN UNLABELED CONTINUE
Use of Unlabeled Continues in the while loop
In a do-while loop, Use an Unlabeled Continue
Use of Unlabeled Continues in a for loop
KOTLIN LABELED CONTINUES
Use of Labeled Continues in a while loop
Use of Labeled Continues in a do-while loop
Use of Labeled Continues in a for loop
EXCEPTIONAL HANDLING
Exceptions in Kotlin
Exception Handling in Kotlin
Avoiding NullPointerException
What If We Fail to Deal with Exceptions?
How to Throw an Exception
KOTLIN try-catch block
The try-catch block as an Expression in Kotlin
The final block in Kotlin
Kotlin throw keyword
NESTED try block AND MULTIPLE catch block
Nested try block
Multiple catch block
NULL SAFETY
Nullable and Non-Nullable Sorts in Kotlin
Checking for the null in Conditions
Safe Call operator(?.)
Elvis Operator(?:)
Not null assertion: !! Operator
TYPE CHECKING AND SMART CASTING
Type Checking
Smart Casting
Use of  !is Operator
EXPLICIT TYPE CASTING
Unsafe Cast Operator: as
Safe Cast Operator: as?
REGEX AND RANGES
Regular Expressions in Kotlin
Regex Functions
RANGES IN KOTLIN
(..) operator
rangeTo() Function
downTo() Function
Range Using the forEach loop
step()
reverse() Function
Various Predefined Functions in the Range
CHAPTER 2: OOP in Kotlin
OBJECTS AND CLASSES
Object-Oriented Programming Language
Class
Object
NESTED CLASS AND INNER CLASS IN KOTLIN
Nested Class
Inner Class in Kotlin
Inner-Class Kotlin Program
SETTERS AND GETTERS
Setters and Getters
Program of Default Setter and Getter in Kotlin
Identifiers for Values and Fields
Private Modifier
Setter and Getter with Custom Parameters
CLASS PROPERTIES AND CUSTOM ACCESSORS
Property
Customer Accessors
KOTLIN CONSTRUCTOR
Primary Constructor
Primary Constructor with Initializer Block
The Default Value in the Primary Constructor
Secondary Constructor
VISIBILITY MODIFIERS IN KOTLIN
Public Modifier
Private Modifier
Internal Modifier
Protected Modifier
Overriding the Protected Modifier
Constructor Visibility
INTERFACES IN KOTLIN
Creating Interfaces
Implementing Interfaces
Default Methods and Default Values
Interface Properties
Interface Inheritance
Implementation of Multiple Interfaces
DATA CLASSES
Rules for Creating Data Classes
toString()
copy()
hashCode() and equals()
SEALED CLASSES
KOTLIN ABSTRACT CLASS
Multiple Derived Classes
INHERITANCE IN KOTLIN
Inheritance Use
Primary Constructor for an Inheritance
Secondary Constructor for an Inheritance
Overriding Member Functions and Attributes
Calling Superclass Implementation
COMPOSITION
Substitution Principle of Liskov
Antipatterns of Implementation Inheritance
Inheritance of a Single Implementation
Tight Coupling
Unnecessary Exposure of Superclass APIs
Exploding Numbers of Subclasses
Composition Refactoring
UserMediator Class Is Being Refactored
From Composition to Aggregation
Handling the Exposure Issue
Composition over Inheritance
The Kotlin Method
ENCAPSULATION
POLYMORPHISM
ENCAPSULATION AND PROCEDURAL PROGRAMMING IN KOTLIN
Example of Procedural Programming
OOP
Tips for Choosing between Procedural and OOP
Procedural
OOP and Encapsulation
Putting Everything Together
CHAPTER 3: Usability Aspects of Kotlin
NULL SAFETY IN KOTLIN
Nullable and Non-Nullable Types in Kotlin
Nullable Types
Non-Nullable Types
Checking for Null in the Conditions
SMART CAST
Use of is for the Smart Cast
Use of !is for the Smart Cast
UNSAFE AND SAFE CAST OPERATOR
Unsafe Cast Operator: as
Safe Cast Operator: as?
(?:) Elvis Operator
EXTENSION FUNCTION
Extended Library Class Using an Extension Function
Extensions Are Resolved Statically
Nullable Receiver
Companion Object Extensions
OVERLOADING OF THE OPERATOR IN KOTLIN
Unary Operators
Increment and Decrement Operators
Binary Operators
Other Operators
Enum CLASSES IN KOTLIN
Enum Initializing
Enum Properties and Methods
Properties and Functions of the Enum Class
Enums as Anonymous Classes
Usage of when Expression with the Enum Class
KOTLIN GENERICS
Generic Usage in Our Program
Variance
The out Keyword
The in Keyword
Covariance
Contra Covariance
Type Projections
Star Projections
CHAPTER 4: Kotlin Functional Programming
LAMBDA EXPRESSIONS AND ANONYMOUS FUNCTIONS IN KOTLIN
LAMBDA EXPRESSION
Inference in Lambda Types
Type Declaration in Lambdas
it: Implicit Name of a Single-Parameter
Returning a Value from a Lambda Expression
ANONYMOUS FUNCTION
Return Type and Parameters
The Distinction between Lambda Expressions and Anonymous Functions
HIGHER-ORDER FUNCTIONS IN KOTLIN
Higher-Order Function
Returning a Function from a Higher-Order Function
KOTLIN LOCAL FUNCTIONS
SCOPE FUNCTION IN KOTLIN
SCOPE FUNCTIONS
Utilization of Scope Functions
Scope Function Types
Object References
Return Values
KOTLIN COLLECTIONS
Types of Collections
Immutable Collection
Mutable Collection
ArrayList IN KOTLIN
listOf() IN KOTLIN
Indexing List Elements in Kotlin
The First and Last Elements
Iteration Methods for Lists
Sorting the List’s Elements
The Functions contains() and containsAll()
setOf() in Kotlin
Set Indexing
Set Basics
The Functions contains() and containsAll()
mutableSetOf() METHOD IN KOTLIN
Set Indexing
Set the First and Last Element
Traversal in a mutableSet
The Methods contains() and containsAll()
hashSetOf() IN KOTLIN
hashSet Traversal
Indexing in a hashSet
The Functions contains() and containsAll()
mapOf () in Kotlin
Map Size
Empty Map
Get Map Values
Map Contains Keys or Values
Two Values and the Same Key
HashMap IN KOTLIN
HashMap Functions Use
HashMap Time Complexity
CHAPTER 5: Code Management and Exception Handling
EXCEPTIONAL HANDLING | TRY, CATCH, THROW, AND FINALLY
Exceptions in Kotlin
Exception Handling
What If We Don’t Deal with Exceptions?
How to Throw an Exception in Kotlin
NullPointerException Example
How to Avoid NullPointerException
KOTLIN try-catch block
Kotlin try-catch block as an Expression
Kotlin Finally Block
Kotlin throw Keyword
NESTED try block AND MULTIPLE catch block
Nested try block
Multiple catch block
LOGGING IN KOTLIN
The Easiest Kotlin Logging That Could Work
What Is Application Logging?
Using Logback for Kotlin Logging
Add Logback to Our Project
Calling LogBack from Kotlin
Why Log?
What Logging Method Should We Use?
Configuring Logger
Formatting Kotlin Logging Messages
Logging to a File
Setting Kotlin Logging Levels
UNIT TESTING
Simple Android Application
Project Setup
Our First Test
Test Structure
Given Block
When Block
Then Block
Running Test
NOTHING BY KOTLIN: ITS APPLICABILITY IN GENERICS
Key Points
CHAPTER 6: Code Optimization Ideas
OPTIMIZATION TIPS
Using Static Layout Imports in Kotlin
Creating POJO Classes in Kotlin
Constructors and Inheritance in Kotlin
Using Lambda Functions in Kotlin
Tail Recursion, Sealed Classes, Local, Infix, Inline Functions, and More Advanced Kotlin Tips
Local Functions
Infix Functions
Inline Functions
Tail Recursion
Sealed Classes
Some More Helpful Tips
Local Return
Operator Overloading
Lambda Extensions
lateinit
Companion Objects
Tips for Improving Kotlin Compilation Times
General Suggestions
Configuration of Gradle
Configuration of Windows
WRITING SECURE CODE
Set Up Source Code and Tests in Our Android Apps
How Does Kotlin Code Look?
Why Is It Superior to Java?
Adapting an Existing Android Project to Utilize Kotlin
Existing Java Files Can Convert to Kotlin
Writing Tests in the Kotlin
BEST CODING PRACTICES
Accept Immutability
Get Rid of ArrayList and HashMap
Make Use of Functional Constructs
javaClass
String Interpolation
Infer Types
Semantic Test Naming
Safe Operator?
Elvis Throws
List Literals in Annotations
Collection Helpers
No more .equals()
Method Readability – Named Parameters
HOW KOTLIN OUTPERFORMS JAVA IN SOLVING LONG-STANDING SECURITY ISSUES
Typing, Syntax, and Speed Compared
Null Reference Exceptions Pose Security Risks
Kotlin Has Everything That Java Needs
Finally, There Is More to It Than Simply Null
WHAT EXACTLY IS APPLICATION HARDENING?
What Is the Purpose of Application Hardening?
Is Our Application in Need of Hardening?
Application Hardening Methods
Benefits of Application Hardening
Application Patches
CHAPTER 7: Kotlin for Android Development
BUILDING ANDROID Apps IN KOTLIN
Download and Install Android Studio
Create Our First Project
EXPLORE LAYOUT EDITOR
ADD COLOR RESOURCES
ADD VIEWS AND CONSTRAINTS
CHANGE THE LOOK OF THE BUTTONS AND THE TextView
BENEFITS OF KOTLIN FOR ANDROID App DEVELOPMENT
The Benefits of Kotlin-Based Android App Development
INTEGRATE in-app REVIEWS
Set Up Our Development Environment
Create ReviewManager
Request ReviewInfo Object
Launch in-app Review Flow
APPRAISAL
CHEAT SHEET
BIBLIOGRAPHY
INDEX