Head First Kotlin

Book description

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.

Publisher resources

View/Submit Errata

Table of contents

  1. Authors of Head First Kotlin
  2. how to use this book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. We know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did:
    6. Here’s what YOU can do to bend your brain into submission
    7. Read me
    8. The technical review team
    9. Acknowledgments
    10. O’Reilly
  3. Table of Contents (the real thing)
  4. 1. getting started: A Quick Dip
    1. Welcome to Kotlinville
      1. It’s crisp, concise and readable
      2. You can use object-oriented AND functional programming
      3. The compiler keeps you safe
    2. You can use Kotlin nearly everywhere
      1. Java Virtual Machines (JVMs)
      2. Android
      3. Client-side and server-side JavaScript
      4. Native apps
    3. What we’ll do in this chapter
    4. Install IntelliJ IDEA (Community Edition)
    5. Let’s build a basic application
      1. 1. Create a new project
      2. 2. Specify the type of project
      3. 3. Configure the project
    6. You’ve just created your first Kotlin project
    7. Add a new Kotlin file to the project
    8. Anatomy of the main function
    9. Add the main function to App.kt
      1. Test drive
      2. What the Run command does
    10. What can you say in the main function?
    11. Loop and loop and loop...
      1. Simple boolean tests
    12. A loopy example
      1. Test drive
    13. Conditional branching
    14. Using if to return a value
    15. Update the main function
      1. Test drive
    16. Code Magnets
    17. Using the Kotlin interactive shell
    18. You can add multi-line code snippets to the REPL
      1. It’s exercise time
    19. Code Magnets Solution
    20. Your Kotlin Toolbox
  5. 2. basic types and variables: Being a Variable
    1. Your code needs variables
      1. A variable is like a cup
    2. What happens when you declare a variable
      1. The value is transformed into an object...
      2. ...and the compiler infers the variable’s type from that of the object
    3. The variable holds a reference to the object
      1. val vs. var revisited
    4. Kotlin’s basic types
      1. Integers
      2. Floating points
      3. Booleans
      4. Characters and Strings
    5. How to explicitly declare a variable’s type
      1. Declaring the type AND assigning a value
    6. Use the right value for the variable’s type
    7. Assigning a value to another variable
    8. We need to convert the value
      1. An object has state and behavior
      2. How to convert a numeric value to another type
    9. What happens when you convert a value
    10. Watch out for overspill
    11. Store multiple values in an array
      1. How to create an array
    12. Create the Phrase-O-Matic application
    13. Add the code to PhraseOMatic.kt
    14. The compiler infers the array’s type from its values
      1. How to explicitly define the array’s type
    15. var means the variable can point to a different array
    16. val means the variable points to the same array forever...
      1. ...but you can still update the variables in the array
    17. Code Magnets
    18. Code Magnets Solution
    19. Your Kotlin Toolbox
  6. 3. functions: Getting Out of Main
    1. Let’s build a game: Rock, Paper, Scissors
      1. How the game will work
    2. A high-level design of the game
    3. Here’s what we’re going to do
      1. Get started: create the project
    4. Get the game to choose an option
      1. Create the Rock, Paper, Scissors array
    5. How you create functions
      1. You can send things to a function
    6. You can send more than one thing to a function
      1. Calling a two-parameter function, and sending it two arguments
      2. You can pass arguments to a function so long as the argument type matches the parameter type
    7. You can get things back from a function
      1. Functions with no return value
    8. Functions with single-expression bodies
      1. Create the getGameChoice function
    9. Code Magnets
    10. Code Magnets Solution
    11. Add the getGameChoice function to Game.kt
    12. Behind the scenes: what happens
    13. The story continues
    14. The getUserChoice function
      1. Ask for the user’s choice
    15. How for loops work
      1. Looping through a range of numbers
      2. Use downTo to reverse the range
      3. Use step to skip numbers in the range
      4. Looping through the items in an array
    16. Ask the user for their choice
      1. Use the readLine function to read the user’s input
    17. We need to validate the user’s input
      1. ‘And’ and ‘Or’ operators (&& and ||)
      2. Not equals (!= and !)
      3. Use parentheses to make your code clear
    18. Add the getUserChoice function to Game.kt
      1. Test drive
      2. We need to print the results
    19. Add the printResult function to Game.kt
      1. Test drive
    20. Your Kotlin Toolbox
  7. 4. classes and objects: A Bit of Class
    1. Object types are defined using classes
      1. You can define your own classes
    2. How to design your own classes
    3. Let’s define a Dog class
    4. How to create a Dog object
    5. How to access properties and functions
      1. What if the Dog is in a Dog array?
    6. Create a Songs application
      1. Test drive
    7. The miracle of object creation
    8. How objects are created
      1. What the Dog constructor looks like
    9. Behind the scenes: calling the Dog constructor
    10. Code Magnets
    11. Code Magnets Solution
    12. Going deeper into properties
      1. Behind the scenes of the Dog constructor
    13. Flexible property initialization
    14. How to use initializer blocks
    15. You MUST initialize your properties
    16. How do you validate property values?
      1. The solution: custom getters and setters
    17. How to write a custom getter
    18. How to write a custom setter
    19. The full code for the Dogs project
      1. Test drive
    20. Your Kotlin Toolbox
  8. 5. subclasses and superclasses: Using Your Inheritance
    1. Inheritance helps you avoid duplicate code
      1. An inheritance example
    2. What we’re going to do
    3. Design an animal class inheritance structure
    4. Use inheritance to avoid duplicate code in subclasses
    5. What should the subclasses override?
      1. The animals have different property values...
      2. ...and different function implementations
    6. We can group some of the animals
    7. Add Canine and Feline classes
    8. Use IS-A to test your class hierarchy
      1. Use HAS-A to test for other relationships
    9. The IS-A test works anywhere in the inheritance tree
    10. We’ll create some Kotlin animals
    11. Declare the superclass and its properties and functions as open
    12. How a subclass inherits from a superclass
    13. How (and when) to override properties
    14. Overriding properties lets you do more than assign default values
    15. How to override functions
      1. The rules for overriding functions
    16. An overridden function or property stays open...
      1. ...until it’s declared final
    17. Add the Hippo class to the Animals project
    18. Code Magnets
    19. Code Magnets Solution
    20. Add the Canine and Wolf classes
    21. Which function is called?
    22. Inheritance guarantees that all subclasses have the functions and properties defined in the superclass
      1. Any place where you can use a superclass, you can use one of its subclasses instead
    23. When you call a function on the variable, it’s the object’s version that responds
    24. You can use a supertype for a function’s parameters and return type
    25. The updated Animals code
      1. Test drive
    26. Your Kotlin Toolbox
  9. 6. abstract classes and interfaces: Serious Polymorphism
    1. The Animal class hierarchy revisited
    2. Some classes shouldn’t be instantiated
      1. Declare a class as abstract to stop it from being instantiated
    3. Abstract or concrete?
    4. An abstract class can have abstract properties and functions
      1. We can mark three properties as abstract
    5. The Animal class has two abstract functions
    6. How to implement an abstract class
    7. You MUST implement all abstract properties and functions
    8. Let’s update the Animals project
      1. Test drive
    9. Independent classes can have common behavior
    10. An interface lets you define common behavior OUTSIDE a superclass hierarchy
    11. Let’s define the Roamable interface
      1. Interface functions can be abstract or concrete
    12. How to define interface properties
    13. Declare that a class implements an interface...
      1. ...then override its properties and functions
    14. How to implement multiple interfaces
    15. How do you know whether to make a class, a subclass, an abstract class, or an interface?
    16. Update the Animals project
      1. Test drive
    17. Interfaces let you use polymorphism
      1. Access uncommon behavior by checking an object’s type
    18. Where to use the is operator
      1. As the condition for an if
      2. In conditions using && and ||
      3. In a while loop
    19. Use when to compare a variable against a bunch of options
    20. The is operator usually performs a smart cast
    21. Use as to perform an explicit cast
    22. Update the Animals project
      1. Test drive
    23. Your Kotlin Toolbox
  10. 7. data classes: Dealing with Data
    1. == calls a function named equals
    2. equals is inherited from a superclass named Any
      1. The importance of being Any
    3. The common behavior defined by Any
    4. We might want equals to check whether two objects are equivalent
    5. A data class lets you create data objects
      1. How to create objects from a data class
    6. Data classes override their inherited behavior
      1. The equals function compares property values
      2. Equal objects return the same hashCode value
      3. toString returns the value of each property
    7. Copy data objects using the copy function
    8. Data classes define componentN functions...
      1. ...that let you destructure data objects
    9. Create the Recipes project
      1. Test drive
    10. Generated functions only use properties defined in the constructor
    11. Initializing many properties can lead to cumbersome code
      1. Default parameter values to the rescue!
    12. How to use a constructor’s default values
      1. 1. Passing values in order of declaration
      2. 2. Using named arguments
    13. Functions can use default values too
    14. Overloading a function
      1. Dos and don’ts for function overloading:
    15. Let’s update the Recipes project
    16. The code continued...
      1. Test drive
    17. Your Kotlin Toolbox
  11. 8. nulls and exceptions: Safe and Sound
    1. How do you remove object references from variables?
    2. Remove an object reference using null
      1. Why have nullable types?
    3. You can use a nullable type everywhere you can use a non-nullable type
    4. How to create an array of nullable types
    5. How to access a nullable type’s functions and properties
    6. Keep things safe with safe calls
    7. You can chain safe calls together
      1. What happens when a safe call chain gets evaluated
    8. The story continues
    9. You can use safe calls to assign values...
      1. ...and assign values to safe calls
    10. Use let to run code if values are not null
    11. Using let with array items
      1. Using let to streamline expressions
    12. Instead of using an if expression...
      1. ...you can use the safer Elvis operator
    13. The !! operator deliberately throws a NullPointerException
    14. Create the Null Values project
    15. The code continued...
      1. Test drive
    16. An exception is thrown in exceptional circumstances
      1. You can catch exceptions that are thrown
    17. Catch exceptions using a try/catch
    18. Use finally for the things you want to do no matter what
    19. An exception is an object of type Exception
    20. You can explicitly throw exceptions
    21. try and throw are both expressions
      1. How to use try as an expression
      2. How to use throw as an expression
    22. Code Magnets
    23. Code Magnets Solution
    24. Your Kotlin Toolbox
  12. 9. collections: Get Organized
    1. Arrays can be useful...
    2. ...but there are things an array can’t handle
      1. You can’t change an array’s size
      2. Arrays are mutable, so they can be updated
    3. When in doubt, go to the Library
    4. List, Set and Map
      1. List - when sequence matters
      2. Set - when uniqueness matters
      3. Map - when finding something by key matters
    5. Fantastic Lists...
      1. ...and how to use them
    6. Create a MutableList...
      1. ..and add values to it
    7. You can remove a value...
      1. ...and replace one value with another
    8. You can change the order and make bulk changes...
      1. ...or take a copy of the entire MutableList
    9. Create the Collections project
      1. Test drive
    10. Code Magnets
    11. Code Magnets Solution
    12. Lists allow duplicate values
    13. How to create a Set
      1. How to use a Set’s values
    14. How a Set checks for duplicates
    15. Hash codes and equality
      1. Equality using the === operator
      2. Equality using the == operator
    16. Rules for overriding hashCode and equals
    17. How to use a MutableSet
    18. You can copy a MutableSet
    19. Update the Collections project
      1. Test drive
    20. Time for a Map
      1. How to create a Map
    21. How to use a Map
    22. Create a MutableMap
      1. Put entries in a MutableMap
    23. You can remove entries from a MutableMap
    24. You can copy Maps and MutableMaps
    25. The full code for the Collections project
      1. Test drive
    26. Your Kotlin Toolbox
  13. 10. generics: Know Your Ins from Your Outs
    1. Collections use generics
    2. How a MutableList is defined
      1. Understanding collection documentation (Or, what’s the meaning of “E”?)
    3. Using type parameters with MutableList
    4. Things you can do with a generic class or interface
    5. Here’s what we’re going to do
    6. Create the Pet class hierarchy
    7. Define the Contest class
      1. Declare that Contest uses a generic type
      2. You can restrict T to a specific supertype
    8. Add the scores property
      1. Create the addScore function
    9. Create the getWinners function
    10. Create some Contest objects
      1. The compiler can infer the generic type
    11. Create the Generics project
      1. Test drive
    12. The Retailer hierarchy
    13. Define the Retailer interface
    14. We can create CatRetailer, DogRetailer and FishRetailer objects...
      1. ...but what about polymorphism?
    15. Use out to make a generic type covariant
      1. Collections are defined using covariant types
    16. Update the Generics project
      1. Test drive
    17. We need a Vet class
      1. Assign a Vet to a Contest
    18. Create Vet objects
      1. Pass a Vet to the Contest constructor
    19. Use in to make a generic type contravariant
      1. Should a Vet<Cat> ALWAYS accept a Vet<Pet>?
    20. A generic type can be locally contravariant
    21. Update the Generics project
      1. Test drive
    22. Your Kotlin Toolbox
  14. 11. lambdas and higher-order functions: Treating Code Like Data
    1. Introducing lambdas
      1. What we’re going to do
    2. What lambda code looks like
    3. You can assign a lambda to a variable
      1. Execute a lambda’s code by invoking it
    4. What happens when you invoke a lambda
    5. Lambda expressions have a type
    6. The compiler can infer lambda parameter types
      1. You can replace a single parameter with it
    7. Use the right lambda for the variable’s type
      1. Use Unit to say a lambda has no return value
    8. Create the Lambdas project
      1. Test drive
    9. You can pass a lambda to a function
      1. Add a lambda parameter to a function by specifying its name and type
    10. Invoke the lambda in the function body
      1. Call the function by passing it parameter values
    11. What happens when you call the function
    12. You can move the lambda OUTSIDE the ()’s...
      1. ...or remove the ()’s entirely
    13. Update the Lambdas project
      1. Test drive
    14. A function can return a lambda
    15. Write a function that receives AND returns lambdas
      1. Define the parameters and return type
      2. Define the function body
    16. How to use the combine function
      1. What happens when the code runs
      2. You can make lambda code more readable
    17. Use typealias to provide a different name for an existing type
    18. Update the Lambdas project
      1. Test drive
    19. Code Magnets
    20. Code Magnets Solution
    21. Your Kotlin Toolbox
  15. 12. built-in higher-order functions: Power Up Your Code
    1. Kotlin has a bunch of built-in higher-order functions
    2. The min and max functions work with basic types
      1. The minBy and maxBy functions work with ALL types
    3. A closer look at minBy and maxBy’s lambda parameter
      1. What about minBy and maxBy’s return type?
    4. The sumBy and sumByDouble functions
      1. sumBy and sumByDouble’s lambda parameter
    5. Create the Groceries project
      1. Test drive
    6. Meet the filter function
      1. There’s a whole FAMILY of filter functions
    7. Use map to apply a transform to your collection
      1. You can chain function calls together
    8. What happens when the code runs
    9. The story continues...
    10. forEach works like a for loop
    11. forEach has no return value
      1. Lambdas have access to variables
    12. Update the Groceries project
      1. Test drive
    13. Use groupBy to split your collection into groups
    14. You can use groupBy in function call chains
    15. How to use the fold function
    16. Behind the scenes: the fold function
    17. Some more examples of fold
      1. Find the product of a List<Int>
      2. Concatenate together the name of each item in a List<Grocery>
      3. Subtract the total price of items from an initial value
    18. Update the Groceries project
      1. Test drive
    19. Your Kotlin Toolbox
    20. Leaving town...
      1. It’s been great having you here in Kotlinville
  16. A. coroutines: Running Code in Parallel
    1. Let’s build a drum machine
      1. 1. Create a new GRADLE project
      2. 2. Enter an artifact ID
      3. 3. Specify configuration details
      4. 4. Specify the project name
      5. Add the audio files
    2. Add the code to the project
      1. Test drive
      2. Use coroutines to make beats play in parallel
    3. 1. Add a coroutines dependency
      1. 2. Launch a coroutine
      2. Test drive
      3. A coroutine is like a lightweight thread
    4. Use runBlocking to run coroutines in the same scope
      1. Test drive
    5. Thread.sleep pauses the current THREAD
      1. The delay function pauses the current COROUTINE
    6. The full project code
      1. Test drive
  17. B. testing: Hold Your Code to Account
    1. Kotlin can use existing testing libraries
      1. Add the JUnit library
    2. Create a JUnit test class
    3. Using KotlinTest
    4. Use rows to test against sets of data
  18. C. leftovers: The Top Ten Things: (We Didn’t Cover)
    1. 1. Packages and imports
      1. How to add a package
      2. Package declarations
    2. The fully qualified name
      1. Type the fully qualified name...
      2. ...or import it
    3. 2. Visibility modifiers
      1. Visibility modifiers and top level code
    4. Visibility modifiers and classes/interfaces
    5. 3. Enum classes
      1. Enum constructors
    6. enum properties and functions
    7. 4. Sealed classes
      1. Sealed classes to the rescue!
    8. How to use sealed classes
    9. 5. Nested and inner classes
    10. An inner class can access the outer class members
    11. 6. Object declarations and expressions
    12. Class objects...
      1. ...and companion objects
    13. Object expressions
    14. 7. Extensions
    15. 8. Return, break and continue
      1. Using labels with break and continue
    16. Using labels with return
    17. 9. More fun with functions
      1. vararg
      2. infix
      3. inline
    18. 10. Interoperability
      1. Interoperability with Java
      2. Using Kotlin with JavaScript
      3. Writing native code with Kotlin
  19. Index

Product information

  • Title: Head First Kotlin
  • Author(s): Dawn Griffiths, David Griffiths
  • Release date: February 2019
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781491996690