Head First Kotlin: A Brain-Friendly 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"

What will you learn from this book? Head First Kotlin is a complete introduction to coding in Kotlin. This hands-on book helps you learn the Kotlin language with a unique method that goes beyond syntax and how-to manuals and teaches you how to think like a great Kotlin developer. You’ll learn everything from language fundamentals to collections, generics, lambdas, and higher-order functions. Along the way, you’ll get to play with both object-oriented and functional programming. If you want to really understand Kotlin, this is the book for you. Why does this book look so different? Based on the latest research in cognitive science and learning theory, Head First Kotlin uses a visually rich format to engage your mind rather than a text-heavy approach that puts you to sleep. Why waste your time struggling with new concepts? This multisensory learning experience is designed for the way your brain really works.

Author(s): Dawn Griffiths, David Griffiths
Edition: 1
Publisher: O'Reilly Media
Year: 2019

Language: English
Commentary: Vector PDF
Pages: 482
City: Sebastopol, CA
Tags: Programming; Functional Programming; Parallel Programming; Lambda Functions; Object-Oriented Programming; Testing; Kotlin; Polymorphism; Elementary; Higher-Order Functions

Authors of Head First Kotlin
Table of Contents
Intro
how to use this book
Who is this book for?
Who should probably back away from this
We know what you’re thinking
We know what your brain is thinking
Metacognition: thinking about thinking
Here’s what WE did:
Here’s what YOU can do to bend
Read me
The technical review team
Acknowledgments
O’Reilly
Chapter 1: getting started
Welcome to Kotlinville
You can use Kotlin nearly everywhere
What we’ll do in this chapter
Install IntelliJ IDEA (Community Edition
Let’s build a basic application
Building a basic application (continued)
Building a basic application (continued)
You’ve just created your first Kotlin pr
Add a new Kotlin file to the project
Anatomy of the main function
Add the main function to App.kt
Test drive
What can you say in the main function?
Loop and loop and loop...
A loopy example
Conditional branching
Using if to return a value
Update the main function
Using the Kotlin interactive shell
You can add multi-line code snippets to
Messages
MessagesSolution
Your Kotlin Toolbox
Chapter 2: basic types and variables
Your code needs variables
What happens when you declare a variable
The variable holds a reference to the ob
Kotlin’s basic types
How to explicitly declare a variable’s t
Use the right value for the variable’s t
Assigning a value to another variable
We need to convert the value
What happens when you convert a value
Watch out for overspill
Store multiple values in an array
Create the Phrase-O-Matic application
Add the code to PhraseOMatic.kt
The compiler infers the array’s type fro
var means the variable can point to a di
val means the variable points to the sam
References
References Solution
Your Kotlin Toolbox
Chapter 3: functions
Let’s build a game: Rock, Paper, Scissor
Choices
A high-level design of the game
Here’s what we’re going to do
Get the game to choose an option
How you create functions
You can send more than one thing to a fu
You can get things back from a function
Functions with single-expression bodies
Add the getGameChoice function to Game.k
Behind the scenes: what happens
The story continues
The getUserChoice function
How for loops work
How for loops work (continued)
Ask the user for their choice
Messages
MessagesSolution
We need to validate the user’s input
More powerful boolean expressions (conti
Add the getUserChoice function to Game.k
Test drive
Choices
Add the printResult function to Game.kt
The Game.kt code continued
Your Kotlin Toolbox
Chapter 4: classes and objects
Object types are defined using classes
How to design your own classes
Let’s define a Dog class
How to create a Dog object
How to access properties and functions
Create a Songs application
The miracle of object creation
How objects are created
Behind the scenes: calling the Dog const
The story continues...
Going deeper into properties
Flexible property initialization
How to use initializer blocks
You MUST initialize your properties
How do you validate property values?
How to write a custom getter
How to write a custom setter
The full code for the Dogs project
The code continued...
Your Kotlin Toolbox
Chapter 5: subclasses and superclasses
Inheritance helps you avoid duplicate code
What we’re going to do
Design an animal class inheritance structure
Use inheritance to avoidduplicate code in subclasses
What should the subclasses override?
We can group some of the animals
Add Canine and Feline classes
Use IS-A to test your class hierarchy
The IS-A test works anywhere in the inhe
We’ll create some Kotlin animals
Declare the superclass and itsproperties
How a subclass inherits from a superclas
How (and when) to override properties
Overriding properties lets you domore th
How to override functions
An overridden function or property stays
Add the Hippo class to the Animals proje
Add the Canine and Wolf classes
Which function is called?
Inheritance that all subclasses have th
When you call a function on the variable
You can use a supertype for a function’s
The updated Animals code
The code continued...
Your Kotlin Toolbox
Chapter 6: abstract classes and interfaces
The Animal class hierarchy revisited
Some classes shouldn’t be instantiated
Abstract or concrete?
An abstract class can have abstract properties and functions
The Animal class has two abstract functions
How to implement an abstract class
You MUST implement all abstract properties and functions
Let’s update the Animals project
The code continued...
Independent classes can have common behavior
An interface lets you define common behavior OUTSIDE a superclass hierarchy
Let’s define the Roamable interface
How to define interface properties
Declare that a class implements an interface
How to implement multiple interfaces
How do you know whether to make a class,a subclass, an abstract class, or an interface?
Update the Animals project
The code continued...
Interfaces let you use polymorphism
Where to use the operator
Use when to compare a variable against a bunch of options
The is operator performs a smart cast
Use as to perform an explicit cast
Update the Animals project
Your Kotlin Toolbox
Chapter 7: data classes
== calls a function named equals
equals is inherited from a superclass named Any
The common behavior defined by Any
We might want equals to check whether two objects are equivalent
A data class lets you create data object
Data classes override their inherited behavior
Copy data objects using the copy function
Data classes define componentN functions
Create the Recipes project
Messages
MessagesSolution
Generated functions only use properties defined in the constructor
Initializing many properties can lead to cumbersome code
How to use a constructor’s default value
Functions can use default values too
Overloading a function
Let’s update the Recipes project
The code continued...
Your Kotlin Toolbox
Chapter 8: nulls and exceptions
How do you remove object references from variables?
Remove an object reference using null
You can use a nullable type everywhere you can use a non-nullable type
How to create an array of nullable types
How to access a nullable type’s function
Keep things safe with safe calls
You can chain safe calls together
The story continues...
You can use safe calls to assign values.
Use to run code if values are not null
Using let with array items
Instead of using an if expression...
The !! operator deliberately throws a NullPointerException
Create the Null Values project
The code continued...
An exception is thrown in exceptional circumstances
Catch exceptions using a try/catch
Use finally for the things you want to do no matter what
An exception is an object of type Except
You can explicitly throw exceptions
try and throw are both expressions
Your Kotlin Toolbox
Chapter 9: collections
Arrays can be useful...
...but there are things an array can’t handle
When in doubt, go to the Library
List, Set and Map
Fantastic Lists...
Create a MutableList...
You can remove a value...
You can change the order and make bulk changes
Create the Collections project
Lists allow duplicate values
How to create a Set
How a Set checks for duplicates
Hash codes and equality
Rules for overridinghashCode and equals
How to use a MutableSet
You can copy a MutableSet
Update the Collections project
Test drive
Time for a Map
How to use a Map
Create a MutableMap
You can remove entries from a MutableMap
You can copy Maps and MutableMaps
The full code for the Collections project
Test drive
Messages
MessagesSolution
Your Kotlin Toolbox
Chapter 10: generics
Collections use
How a MutableList is defined
Using type parameters with MutableList
Things you can do with a generic class or interface
Here’s what we’re going to do
Create the Pet class hierarchy
Define the Contest class
Add the scores property
Create the getWinners function
Create some Contest objects
Create the Generics project
The code continued...
The Retailer hierarchy
Define the Retailer interface
We can create CatRetailer, DogRetailer and FishRetailer objects
Use to make a generic type
Update the Generics project
The code continued...
We need a Vet class
Create Vet objects
Use in to make a generic type contravariant
A generic type can be locally contravariant
Update the Generics project
The code continued...
Your Kotlin Toolbox
Chapter 11: lambdas and higher-order functions
Introducing lambdas
What lambda code looks like
You can assign a lambda to a variable
What happens when you invoke a lambda
The story continues...
Lambda expressions have a type
The compiler can infer lambda parameter types
Use the right lambda for the variable’s
Create the Lambdas project
Messages
MessagesSolution
You can pass a lambda to a function
Invoke the lambda in the function body
What happens when you call the function
The story continues...
You can move the lambda OUTSIDE the ()’s
Update the Lambdas project
Test drive
A function can return a lambda
Write a function that receives AND returns lambdas
How to use the combine function
The story continues...
Use typealias to provide a different name for an existing type
Update the Lambdas project
The code continued...
Your Kotlin Toolbox
Chapter 12: built-in higher-order functions
Kotlin has a bunch of built-in higher-order functions
The min and max functions work with basic types
A closer look at minBy and maxBy’s lambda parameter
The sumBy and sumByDouble functions
Create the Groceries project
Meet the filter function
Use map to apply a transform to your collection
What happens when the code runs
The story continues...
forEach works like a for loop
forEach has no return value
Update the Groceries project
The code continued...
Use groupBy to split your collection into groups
You can use groupBy in function call chains
How to use the fold function
Behind the scenes: the fold function
The story continues...
Some more examples of fold
Update the Groceries project
The code continued...
Messages
MessagesSolution
Your Kotlin Toolbox
Leaving town...
Appendix i: coroutines
Let’s build a drum machine
Add the code to the project
Test drive
1. Add a coroutines dependency
2. Launch a coroutine
Test drive
Use runBlocking to run coroutines in the same scope
Thread.sleep pauses the current THREAD
The full project code
Test drive
Appendix ii: testing
Kotlin can use existing testing libraries
Create a JUnit test class
Using KotlinTest
Use rows to test against sets of data
Appendix iii: leftovers
1. Packages and imports
The fully qualified name
2. Visibility modifiers
Visibility modifiers and classes/interfaces
3. Enum classes
enum properties and functions
4. Sealed classes
How to use sealed classes
5. Nested and inner classes
An inner class can access the outer class members
6. Object declarations and expressions
Class objects...
Object expressions
7. Extensions
8. Return, break and continue
Using labels with return
9. More fun with functions
10. Interoperability
Index