Mastering Kotlin: A Beginner's 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"

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. However, 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 variable and expression 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 pursue a variety of career routes, spanning fields such as mobile app development, game development, 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 how 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.

Author(s): Sufyan bin Uzayr
Series: Mastering Computer Science
Publisher: CRC Press
Year: 2022

Language: English
Pages: 334
City: Boca Raton

Cover
Half Title
Series Page
Title Page
Copyright Page
Contents
Preface
About the Author
CHAPTER 1: Getting Started
HISTORY OF KOTLIN
FEATURES OF KOTLIN
KOTLIN’S KEY CHARACTERISTICS
HOW KOTLIN MULTIPLATFORM FUNCTIONS
KOTLIN’S ARCHITECTURE
KOTLIN VS. JAVA
KOTLIN MULTIPLATFORM IN MOBILE
Begin with Kotlin Multiplatform Mobile
Platforms That Are Supported
Kotlin for Server-Side
Kotlin Frameworks for Server-Side Development
Using Kotlin to Deploy Server-Side Apps
Kotlin for Android
Kotlin for JavaScript (JS)
Frameworks in Kotlin/JS
Kotlin/Native
Why Is Kotlin/Native Used?
Kotlin for Data Science
Editors Who Work Interactively
Kotlin for Competitive Programming
Kotlin Language Applications
Setup of the Kotlin Environment for Command Line
Intellij IDEA Is Used to Build up a Kotlin Environment
Kotlin Hello Everyone Program
DATA TYPES IN KOTLIN
Integer Data Type
Floating-Point Data Type
Boolean Data Type
Character Data Type
VARIABLES IN KOTLIN
Immutable Using val Keyword
Variable Scope
Naming Convention
OPERATORS IN KOTLIN
Arithmetic Operator
Relation Operator
Assignment Operator
Unary Operator
Logical Operator
Bitwise Operator
KOTLIN STANDARD INPUT/OUTPUT
Distinction between println() and print()
Variables and Literals Print
Input of Kotlin
Take User Input with the readline() Function
Take Input from the User Using the Scanner Class
Take User Input without Using the Scanner Class
TYPE CONVERSION IN KOTLIN
Conversion of a Larger Data Type to a Smaller Data Type
EXPRESSION, STATEMENT, AND BLOCK IN KOTLIN
Expression in Kotlin
Kotlin if Expression
Statement in Kotlin
Multiple Statements in Kotlin
Block in Kotlin
Variable Scope in Nested Blocks
CONCLUSION
CHAPTER 2: Object-Oriented Programming (OOP) Concepts
OBJECTS AND CLASSES IN KOTLIN
Language for Object-Oriented Programming
Class
Object
NESTED CLASS AND INNER CLASS IN KOTLIN
Nested Class
In Comparison to Java
Kotlin Inner Class
Inner-Class Kotlin Program
SETTERS AND GETTERS IN KOTLIN
Setters and Getters
Default Setter and Getter Kotlin Program
Identifiers for Values and Fields
Private Modifier
Setter and Getter with Custom Parameters
CLASS PROPERTIES AND CUSTOM ACCESSORS IN KOTLIN
Property
Customer Accessors
KOTLIN CONSTRUCTOR
Primary Constructor
Primary Constructor with Initializer Block
Secondary Constructor
KOTLIN VISIBILITY MODIFIERS
Public Modifier
Private Modifier
Internal Modifier
Protected Modifier
Overriding of Protected Modifier
Constructor Visibility
INHERITANCE IN KOTLIN
Inheritance Use
Primary Constructor for Kotlin Inheritance
Secondary Constructor for Kotlin Inheritance
Overriding Member Functions and Properties
Calling the Superclass Implementation
INTERFACES IN KOTLIN
Interfaces Creating
Default Methods and Default Values
Interface Properties
Interface Inheritance
Implementation of Multiple Interfaces
DATA CLASSES IN KOTLIN
Data Class Creation Rules
toString()
copy()
hashCode() and equals()
KOTLIN SEALED CLASSES
Sealed Class with When
KOTLIN ABSTRACT CLASS
Multiple Derived Classes
ENUM CLASSES IN KOTLIN
Enums Initializing
Enums Properties and Methods
Properties and Functions of the Enum Class
Enums as Anonymous Classes
Usage of When Expression with Enum Class
KOTLIN EXTENSION FUNCTION
Extended Library Class Using an Extension Function
Extensions Are Resolved Statically
Nullable Receiver
Companion Object Extensions
KOTLIN GENERICS
Generic Usage in Our Program
VARIANCE
The out Keyword
The in Keyword
COVARIANCE
CONTRACOVARIANCE
TYPE PROJECTIONS
STAR PROJECTIONS
CONCLUSION
CHAPTER 3: Exceptional Handling, Null Safety, and Regex and Ranges
EXCEPTIONAL HANDLING IN KOTLIN | TRY, CATCH, THROW, AND FINALLY
Exceptions in Kotlin
What If We Don’t Handle Exceptions?
How to Throw an Exception in Kotlin
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 IN KOTLIN
Nested Try Block
Multiple Catch Block
NULL SAFETY
Nullable and Non-Nullable Sorts in Kotlin
Checking for the Null in Conditions
Safe Call Operator(?.)
run() Method
Elvis Operator(?:)
Not-Null Assertion (!!) Operator
TYPE CHECKING AND SMART CASTING IN KOTLIN
Type Checking
Using When Expression
Smart Casting
Use of !is Operator
EXPLICIT TYPE CASTING IN KOTLIN
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 forEach Loop
CONCLUSION
CHAPTER 4: Control Flow Statements
IF-ELSE EXPRESSION IN KOTLIN
If Statement
If-Else Statement
If-Else Expression in Kotlin as Ternary Operator
If-Else-If Ladder Expression
Nested If Expression
WHILE LOOP IN KOTLIN
DO-WHILE LOOP IN KOTLIN
Working 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
WHEN EXPRESSION IN KOTLIN
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 When Block
Check Whether the Input Value Is Inside the Range
Check Whether a Provided Variable Is of a Specific Type
Using When as a Replacement for an If-Else-If Chain
Verify If a String Includes a Certain Prefix or Suffix
UNLABELED BREAK IN KOTLIN
Use of Unlabeled Break in a While Loop
Use of Unlabeled Break in a Do-While Loop
Use of Unlabeled Break in a For Loop
LABELED BREAK IN KOTLIN
Use of Labeled Break in a While Loop
Use of Labeled Break in a Do-While Loop
Use of Labeled Break in a For Loop
UNLABELED CONTINUE IN KOTLIN
Use of Unlabeled Continue in a While Loop
Use of Unlabeled Continue in a Do-While Loop
Use of Unlabeled Continue in a For Loop
LABELED CONTINUE IN KOTLIN
Use of Labeled Continue in a While Loop
Use of Labeled Continue in a Do-While Loop
Use of Labeled Continue in a For Loop
CONCLUSION
CHAPTER 5: Arrays and Strings, Functions, and Java Interoperability
ARRAYS IN KOTLIN
Creation of an Array
Making Use of the arrayOf() Function
Making Use of the Array Constructor
Array Access and Modification
Array Traversal
STRING IN KOTLIN
Creation of an Empty String
Templates and String Elements
String Literals
Escaped String
Raw String – Multiline String
Escape Characters
String Equality
Structural Equality
Referential Equality
FUNCTIONS IN KOTLIN
Standard Library Function in Kotlin
Kotlin User-Defined Function
Calling a User-Defined Function
DEFAULT AND NAMED ARGUMENTS IN KOTLIN
Default Arguments in Kotlin
No Arguments Are Passed While Calling a Function
Partial Arguments Are Passed While Calling a Function
All Arguments Are Passed While Calling a Function
Named Arguments in Kotlin
RECURSION IN KOTLIN
Normal Function Call
Recursive Function Call
TAIL RECURSION IN KOTLIN
Benefits of Employing Tail Recursion
LAMBDA EXPRESSIONS AND ANONYMOUS FUNCTIONS IN KOTLIN
Lambda Expressions
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
Distinction between Lambda Expressions and Anonymous Functions
INLINE FUNCTIONS IN KOTLIN
Non-Local Control Flow
Crossline Keyword
Noinline
Reified Type Parameters
Properties of Inline
INFIX FUNCTION NOTATION IN KOTLIN
Standard Library Infix Function Notation
Notation for User-Defined Infix Functions
Infix Function Precedence over Operators
HIGHER-ORDER FUNCTIONS IN KOTLIN
Higher-Order Function
Returning a Function from a Higher-Order Function
JAVA INTEROPERABILITY – USING JAVA TO CALL KOTLIN
Properties of Kotlin
Package-Level Functions
Static Fields
Static Methods
Instance Fields
Checked Exceptions
JAVA INTEROPERABILITY – USING KOTLIN TO CALL JAVA
Getters and Setters in Java
Methods
Static Members
Java Arrays
Java Varargs
Types in Java and Kotlin Are Not the Same
CONCLUSION
CHAPTER 6: Collections in Kotlin
COLLECTIONS IN KOTLIN
Types of Collections
Immutable Collection
Mutable Collection
ARRAYLIST IN KOTLIN
Most Important Methods
LISTOF() IN KOTLIN
Indexing List Elements in Kotlin
The First and Last Elements
Iteration Methods for Lists
Sorting the List’s Elements
Contains() and ContainsAll() Functions
SetOf () in Kotlin
Set Indexing
Set Basics
Contains() and ContainsAll() Functions
MUTABLESETOF() METHOD IN KOTLIN
Adding and Deleting Elements from a Set
Set Indexing
Set the First and Last Element
Traversal in a MutableSet
Contains() and ContainsAll() Methods
HASHSETOF() IN KOTLIN
Adding and Deleting Elements from a HashSet
HashSet Traversal
Indexing in a HashSet
Contains() and ContainsAll() Functions
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 Time Complexity
ANNOTATIONS IN KOTLIN
Using Annotation
Declaring Annotation
Annotate a Constructor
Annotate a Property
Several Built-in Annotations
@Target
@Retention
@Repeatable
REFLECTION IN KOTLIN
Class References
Function References
Property References
Constructor References
OVERLOADING OF THE KOTLIN OPERATOR
Unary Operators
Increment and Decrement Operators
Binary Operators
Other Operators
KOTLIN DESTRUCTURING DECLARATIONS
Destructuring Declaration in Lambdas
EQUALITY EVALUATION
Structural Equality
Referential Equality
KOTLIN COMPARATOR
Function
Functions of Extension
CONCLUSION
CHAPTER 7: Android Development with Kotlin
KOTLIN FOR ANDROID
How to Install and Configure Android Studio for Kotlin Development
How to Make an Android Studio Project Using Kotlin
HELLOO WORLD APP IN KOTLIN
HOW TO SET UP AN ANDROID VIRTUAL DEVICE (AVD)
KOTLIN ANIMATIONS FOR ANDROID
Make a New Project
Change the activity_main.xml File
bounce.xml
fade in.xml
fade_out.xml
rotate.xml
slide_down.xml
slide_up.xml
zoom_in.xml
zoom_out.xml
Create MainActivity.kt File
AndroidManifest.xml File
KOTLIN ANDROID FADE IN/OUT
Modify activity_main.xml File
Add an anim Folder
Change the MainActivity.kt File
AndroidManifest.xml File
MENUS FOR ANDROID
How Can We Define a Menu in an XML File?
Different Sorts of Menus in Android
Kotlin Progress Alerts for Android
Take Note of Notification Channels
STRUCTURE OF THE ANDROID PROJECT FOLDER
Manifests Folder
Java Folder
Resource (res) Folder
Gradle Scripts Folder
CONCLUSION
APPRAISAL
BIBLIOGRAPHY
INDEX