Kotlin is an exciting new language that runs on Windows, macOS and Linux operating systems. It has also been adopted by Google as their preferred language for Android development. This textbook assumes very little knowledge of programming so whether you have dabbled with a little JavaScript, played with a bit of Python, written Java or have virtually no programming experience at all you will find that it is for you. The first part of the book introduces Kotlin program structures as well as conditional flow of control features such as if and when expressions as well as iteration loops such as for, while and do-while. Subsequent chapters explain how functions are implemented in Kotlin and introduce concepts from functional programming such as higher order functions and curried functions. The second part focusses on object oriented programming techniques, these include classes, inheritance, abstraction and interfaces. The third part presents container data types such as Arrays, and collections including Lists, Sets and Maps and the fourth part considers concurrency and parallelism using Kotlin coroutines. The book concludes with an introduction to Android mobile application development using Kotlin. Clear steps are provided explaining how to set up your environment and get started writing your own Kotlin programs. An important aspect of the book is teaching by example and there are many examples presented throughout the chapters. These examples are supported by a public GitHub repository that provides complete working code as well as sample solutions to the chapter exercises. This helps illustrate how to write well structured, clear, idiomatic Kotlin to build real applications Preface Chapter Organization What You Need Using an IDE Downloading the IntelliJ IDEA IDE Conventions Example Code and Sample Solutions Contents 1 Introduction What is Kotlin? Kotlin Versions Kotlin Programming Kotlin Libraries Kotlin Execution Environment Where is Kotlin Used Kotlin JVM Environment Kotlin Documentation Running Kotlin Programs Interactively Using the Kotlin REPL Interpreter Running a Kotlin File Executing a Kotlin Script Using Kotlin in an IDE Useful Resources Part I Kotlin Programming 2 A First Kotlin Program Introduction Hello World Setting up Your Program Starting up Kotlin Create a New Kotlin File Create the Main Function Interactive Hello World Variables Vals and Vars String Formatting Naming Conventions Assignment Operator Kotlin Statements and Expressions Comments in Code Basic Types Unsigned Integer Types Numeric Conversions Online Resources Exercises 3 Flow of Control Introduction Operators Comparison Operators Logical Operators Numeric Operators Assignment Operators The if Statement Working with an if Statement Else in an if Statement The Use of Else If Kotlin if Expression Nesting if Statements Null and Conditional Statements Explicitly Checking for Null Conditions The Safe Call Operator The Elvis Operator The Not-Null Assertion Operator Smart Compilation Safe Casting to Non Null Type When Expression While Loop Do Loop For Loop Repeat Loops Loop Control Statements Break Loop Statement Continue Loop Statement When with Continue and Break A Note on Loop Variable Naming Dice Roll Game Online Resources Exercises Check Input is Positive or Negative Test if a Number is Odd or Even Kilometres to Miles Converter Calculate the Factorial of a Number 4 Number Guessing Game Introduction Setting Up the Program What Will the Program Do? Creating the Game Generate the Random Number Obtain an Input from the User Check to See if the Player Has Guessed the Number Check They Haven't Exceeded Their Maximum Number of Guess Notify the Player Whether Higher or Lower End of Game Status The Complete Listing Hints Blank Lines Within a Block of Code Exercises 5 Functions in Kotlin Introduction What Are Functions? Defining Functions An Example Named Function Function Parameters A Function with Parameters Multiple Parameter Functions Default Parameter Values Named Arguments Arbitrary Number of Arguments Parameters Are Vals Returning Values from Functions Anonymous Functions Single Expression Functions Lambdas Lambdas Versus Anonymous Functions Recursive Functions Calculating Factorial Recursively Tail Recursion Optimisation Inline Functions Online Resources Exercises Calculate Prime Numbers Adding Functions to the Number Guess Game 6 Higher Order Functions Introduction Recap on Functions in Kotlin Functions as Entities Box Operator Higher Order Function Concepts Higher Order Function Example Higher Order Functions and Lambdas Using Higher Order Functions Functions Returning Functions Online Resources Exercises 7 Curried Functions Introduction Currying Concepts Kotlin and Curried Functions Closure Online Resources Exercises Part II Object-Oriented Kotlin 8 Kotlin Classes Introduction Classes What are Classes for? What Should a Class Do? Class Terminology Classes Versus Instances Class Definitions Working with the Class Person Be Careful with Assignment Working with Properties Accessing Member Properties Using String Templates Updating Properties Classes and Constructors Simplifying the Class Person Primary Constructors Defining Default Constructor Parameters Named Constructor Parameters Private Properties Auxiliary Constructors Initialisation Behaviour Defining Instance Behaviour Writing Member Functions Member Functions with Parameters Member Functions Returning Values Parameters Are Vals Named Member Function Parameters Default Parameter Values Variable Parameter Lists The This Reference Referencing Member Functions Single Expression Member Functions Defining a Default String Representation Providing KDoc Equality Between Instances Automatic Memory Management Class Design Considerations Online Resources Exercises 9 Objects and Companion Objects Introduction Singleton Objects Singleton Objects in Kotlin Anonymous Objects Companion Objects Companion Object Behaviour An Object or An Instance Online Resources Book References Exercises 10 Further Kotlin Properties Introduction Property Declarations Types Held by a Property Top Level Properties Constructor Parameters Member Level Properties Property Visibility Property Declaration Modifiers Applying const to val Properties Applying lateinit to var Properties Applying Lazy Initialisation to val Properties Summary Creating Custom Property Setters and Getters Using an Implicit Backing Field Using an Explicit Backing Field Properties Without a Backing Field Modifying Setter Visibility GameObject with Properties Online Resources Exercises 11 Scope and Conditional Functions Introduction The User Class The Apply Scope Function The Also Scope Function The Run Scope Function The Let Scope Function The with Scope Function Scope Functions and Nullability Scope Function Categories Conditional Functions Exercises 12 Class Inheritance Introduction What is Inheritance? Terminology Around Inheritance Types of Hierarchy Purpose of Subclasses Kotlin Class Hierarchy Kotlin Classes and Inheritance Objects and Inheritance Anonymous Objects and Inheritance The Class Any and Inheritance Inheritance and Member Functions Overriding Member Functions Declaring Member Functions as Open Inheritance and Properties Extending Behaviour Using Super Casting and Inheritance Smart Casting Checking the Type Explicit Casts Safe Casts Closing a Member Closing Member Functions Closing Properties Inheritance Summary Online Resources Exercises 13 Abstract Classes Introduction Abstract Classes as a Concept Abstract Classes in Kotlin Defining an Abstract Class and Member Functions Subclassing an Abstract Class Abstract Properties Abstract Subclasses Online Resources Exercises 14 Interfaces, Delegation and Enumerated Types Introduction Kotlin Interfaces Defining an Interface Implementing an Interface Objects Can Implement Interfaces Extending a Class and Implementing Interfaces Inheritance by Interfaces Interfaces and Concrete Member Functions Multiple Interfaces with the Same Concrete Member Functions Interface Companion Objects Marker Interfaces Delegation Enumerated Types Kotlin Enums Ordering Enumerated Type Providing Additional Enum Data Online Resources Exercises 15 Packages Introduction Packages Declaring a Package How Packages Relate to Directories Finding a Package Importing a Package Using the Fully Qualified Name Importing a Type, Function or Property Import Options Dealing with Name Clashes Kotlin Default Imports Visibility Modifiers Visibility Modifiers and Constructors Online Resources Exercise 16 Nested/Inner Types Introduction What are Nested/Inner Types Nested Types Member Inner Classes/Anonymous Objects Member Function Inner Classes/Objects Function Inner Classes/Objects Online Resources Exercise 17 Data Classes Introduction Defining Data Classes Data Classes with Non Constructor Properties Data Classes and Inheritance Data Classes and Interfaces Copying Data Classes Data Classes and De-structuring Exercise 18 Sealed and Inline Classes and Typealias Introduction Sealed Classes Sealed Classes in Kotlin 1.4 Sealed Classes and Interfaces in Kotlin 1.5 Inline Classes Inline Class Constraints Simple Inline Class Example Additional Inline Class Concepts Typealias 19 Operator Overloading Introduction Why Have Operator Overloading? Why Not Have Operator Overloading? Implementing Operator Overloading Overloading the Operator Member Functions Mutable Data Types Numerical Operators Unary Prefix Operators Postfix Increment and Decrement Operators Comparison Operators Augmented Assignment Operators Containment (in) Operators Infix Named Operators Summary Online Resources Exercises 20 Error and Exception Handling Introduction Errors and Exceptions What is an Exception? What Is Exception Handling? Handling an Exception Multiple Catch Blocks Accessing the Exception Object Jumping to Exception Handlers The Finally Clause Throwing an Exception Try Catch as an Expression Defining an Custom Exception Chaining Exceptions Nesting Exception Handlers Limitations of Try-Catch Functional Exception Handling Accessing the Failure Exception Accessing the Successful Value Treating Result as a Container Recovery Operations Providing Explicit OnFailure and OnSuccess Behaviour Online Resources Exercises 21 Extension Functions and Properties Introduction Extensions Extension Functions Extension Properties Infix Extension Operators Extensions Scope Online Resources Exercises Part III Data Containers 22 Arrays Introduction Kotlin Arrays Creating Arrays Using Class Array Using Specialised Array Classes Using Factory Function arrayOf Specialised arrayOf Functions Create Empty Arrays Create an Array of Different Types Working with Arrays Arrays of Reference Types Working with Primitive Type Arrays Working with User Defined Types Iteration and Arrays Iterating Over an Array Iterating Over the Indices for an Array Multi-Dimensional Arrays Ragged Arrays Array Operations/Functions 23 Collections Introduction Collections Library Kotlin Collection Types 24 Lists Introduction Lists List Creation Using Classes Directly Using Factory Functions Nested Lists Accessing List Data Obtaining the Size of a List Accessing Elements from a List Updating Elements Using an Index Obtaining a Slice or Sub List Adding to a List Inserting Into a List List Concatenation Removing from a List Checking for List Membership Iterating Over Lists List Member Functions Online Resources Exercises 25 Sets Introduction Sets Creating Sets Set Properties and Member Functions Accessing Elements in a Set Working with Sets Checking for Presence of an Element Adding Items to a Set Removing an Item Nesting Sets Set like Operations Online Resources Exercises 26 Maps Introduction Maps Creating a Map Map Properties Working with Maps Accessing Items via Keys Adding a New Entry Changing a Keys Value Removing an Entry Values, Keys and Items Iterating Over Keys Iterating Over Values Iterating Over Map Entries Checking Key Membership Nesting Dictionaries Online Resources Exercises 27 Pairs and Triples Introduction Creating Pairs and Triples Creating Pairs Creating Triples Working with Pairs and Triples Accessing Elements of a Pair or Triple Copying Pairs and Triples Converting Pairs and Tiples to Lists Destructuring Pairs and Triples Nested Pairs and Triples Things You Can’t Do with Pairs and Triples Exercises 28 Generic Types Introduction The Generic Set Class Writing a Generic Type Declaration-Site Variance Generic Functions Generic Constraints Creating a Parameterised Type Exercises 29 Functional Programming and Containers Introduction ForEach Filter Map Flatten FlatMap Sorting Iterables Fold FoldRight Reduce Labelled Return from Lambdas Online Resources Exercises Part IV Concurrent Kotlin 30 Coroutines Introduction Concurrency Parallelism Threads The Problems with Threads Coroutines Introduction Working with Coroutines Adding Coroutine Library Dependencies Implementing a Coroutine Launching Coroutines Suspending Functions Running Multiple Concurrent Coroutines Coroutine Scope Custom Coroutine Scope Coroutine Dispatchers Coroutine Builders/Launchers Coroutine Jobs Online Resources Exercise 31 Coroutine Channel Communications Introduction Coroutine Channels Rendezvous Channel Buffered Channel Unlimited Buffered Channel Conflated Channel Multiple Senders and Receivers Multiple Coroutine Channel Senders Multiple Coroutine Channel Receivers Pipelines Exercise Part V Android Development 32 Android Overview Introduction What is Android? Android Versions Android Programming Languages Android Runtime Deploying to Android Packaging an Application Application Core Building Blocks Core Element Types How Core Elements Fit Together Android JetPack Online Resources 33 Applications and Activities Introduction Android Studio Setting Up a Project Android SDKs Android Studio AVD Creating an Android Application Creating a New Project Run the Application Android Application Basic Application Structure Gradle Build Files Actual Directory Structure HelloWorld Application Online Resources 34 Android Layouts and Events Introduction Activity Uses Layouts Views View Layouts View Hierarchy View Layout Options Linear Layout Constraint Layout Containers Creating Displays Working with the Layout Editor Programmatically Creating Layout Interacting with the Application Event Generation View Handler Architecture Shortcut OnClick Resource Online Resources 35 Android Tic Tac Toe Introduction Classes in the Game Counter Class Move Class The Player Class The ComputerPlayer Class The Board Class The MainActivity Class The Screen Layout Running the Game