Mastering Kotlin

Book description

Explore popular language features, Java to Kotlin interoperability, advanced topics, and practical applications by building a variety of sample projects

Key Features

  • Understand and leverage the syntax, tools, and patterns by writing code in Kotlin
  • Explore practical topics such as Java interop, concurrency with coroutines, and functional programming
  • Discover how to use Kotlin for build targets like Android, iOS, JavaScript, and backend service

Book Description

Using Kotlin without taking advantage of its power and interoperability is like owning a sports car and never taking it out of the garage. While documentation and introductory resources can help you learn the basics of Kotlin, the fact that it's a new language means that there are limited learning resources and code bases available in comparison to Java and other established languages.

This Kotlin book will show you how to leverage software designs and concepts that have made Java the most dominant enterprise programming language. You'll understand how Kotlin is a modern approach to object-oriented programming (OOP). This book will take you through the vast array of features that Kotlin provides over other languages. These features include seamless interoperability with Java, efficient syntax, built-in functional programming constructs, and support for creating your own DSL. Finally, you will gain an understanding of implementing practical design patterns and best practices to help you master the Kotlin language.

By the end of the book, you'll have obtained an advanced understanding of Kotlin in order to be able to build production-grade applications.

What you will learn

  • Model data using interfaces, classes, and data classes
  • Grapple with practical interoperability challenges and solutions with Java
  • Build parallel apps using concurrency solutions such as coroutines
  • Explore functional, reactive, and imperative programming to build flexible apps
  • Discover how to build your own domain-specific language
  • Embrace functional programming using the standard library and Arrow
  • Delve into the use of Kotlin for frontend JavaScript development
  • Build server-side services using Kotlin and Ktor

Who this book is for

If you're a Kotlin developer looking to further their skills or a professional Java developer looking for better or professional resources in order to make a switch to Kotlin, this book is for you. Familiarity with Kotlin programming will assist with understanding key concepts covered in the book.

Downloading the example code for this ebook: You can download the example code files for this ebook on GitHub at the following link: https://github.com/PacktPublishing/Mastering-Kotlin. If you require support please email: customercare@packt.com

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Kotlin
  3. Dedication
  4. About Packt
    1. Why subscribe?
  5. Contributors
    1. About the author
    2. About the reviewer
    3. Packt is searching for authors like you
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Code in Action
      3. Conventions used
    4. Get in touch
      1. Reviews
  7. Section 1: Kotlin – A Modern Solution to Application Development
  8. A New Challenger Approaches
    1. Technical requirements
    2. Creating a modern language for the JVM
      1. What is Kotlin?
        1. Kotlin is flexible
        2. Kotlin is expressive and concise
        3. Kotlin is powerful
        4. Hello Kotlin
      2. Who created Kotlin?
        1. Announcing Kotlin
        2. Motivations for Kotlin
        3. Community involvement
    3. Moving beyond the JVM
      1. Kotlin for Android
      2. Kotlin for the web
        1. Server-side Kotlin
        2. Kotlin to JavaScript
      3. Native and multiplatform Kotlin
    4. Designing Kotlin with best practices in mind
      1. Learning from Java
      2. Best practice by design
    5. Checking in on the current state of Kotlin
      1. Developing Kotlin in the open
      2. Increasing popularity for Kotlin
      3. Learning Kotlin
    6. Summary
    7. Questions
    8. Further reading
  9. Programmers' Multi-Tool – Flexible, Expressive, and Concise
    1. Technical requirements
    2. Picking your programming paradigm
      1. Object-Oriented Programming
      2. Functional programming
      3. Reactive programming
    3. Embracing first-class functions
      1. Function types
        1. Top-level functions
        2. Extension functions
        3. Higher-order functions
      2. Standard library
    4. Fixing the billion-dollar mistake
      1. Defining null and non-null types
      2. Working with null
        1. Null-safe calls
        2. Non-null assertion
        3. Conditional checks
        4. The Elvis operator
    5. Integrating with Java
      1. Using Java from Kotlin
        1. Creating and working with Java classes from Kotlin
        2. Calling static Java methods from Kotlin
      2. Using Kotlin from Java
        1. Creating and working with Kotlin classes from Java
        2. Calling Kotlin functions from Java
      3. Expanding on the interop story
    6. Summary
    7. Questions
    8. Further reading
  10. Section 2: Putting the Pieces Together – Modeling Data, Managing State, and Application Architecture
  11. Understanding Programming Paradigms in Kotlin
    1. Technical requirements
    2. Classifying programming languages
      1. Multi-paradigm languages
      2. Imperative programming languages
        1. Objected-oriented programming languages
      3. Declarative programming languages
        1. Domain Specific Languages
      4. Other programming paradigms
        1. Event-driven programming
        2. Generic programming
    3. Understanding object-oriented programming
      1. Key concepts
        1. Encapsulation
        2. Inheritance
        3. Polymorphism
      2. Object-oriented programming with Kotlin
    4. Functional programming
      1. Key concepts
        1. First-class functions
        2. Pure functions
      2. Functional programming with Kotlin
      3. More to learn
    5. Reactive programming
      1. RxJava
        1. Key concepts in RxJava
          1. Observables
          2. Operators
          3. Threading
        2. RxKotlin
      2. Reactive coroutines
        1. Channels and flow
    6. Summary
    7. Questions
    8. Further reading
  12. First-Class Functions
    1. Technical requirements
    2. Hello functions – first-class support for functions
      1. Writing a basic function
      2. First-class functions
        1. Functions as variables
          1. Read-only function variables
          2. Mutable function variables
          3. Function properties
        2. Functions as arguments
        3. Functions as return values
        4. Top-level functions
    3. Flexibility by design – reducing boilerplate with effective parameters
      1. Adding function parameters
        1. Multiple function parameters
        2. The vararg modifier
          1. Limitations of vararg
      2. Named parameters
      3. Default parameter values
    4. A function for every job – understanding function variations
      1. Top-level functions
      2. Class functions
      3. Local functions
      4. Single expression functions
      5. Infix functions
      6. Extension functions
    5. Summary
    6. Questions
    7. Further reading
  13. Modeling Real-World Data
    1. Technical requirements
    2. Object-oriented programming in Kotlin
      1. Defining a class
        1. Adding properties
          1. Property basics
          2. Working with properties
          3. Custom accessors
          4. Primary constructor properties
        2. Initialization
          1. Primary constructor initialization
          2. Property assignments and initializer blocks
        3. Adding methods
      2. Customizing construction
        1. Primary constructors
        2. Secondary constructors
        3. Private constructors
      3. Controlling visibility
        1. The public modifier
        2. The internal modifier
        3. The protected modifier
        4. The private modifier
      4. Organizing your code
        1. Files and classes
        2. Packages
        3. Modules
    3. Achieving inheritance and composition
      1. Interfaces
        1. Defining a simple interface
        2. Defining an interface property
        3. Interface inheritance
        4. Implementing multiple interfaces
        5. Default methods
      2. Subclasses and abstract classes
      3. Nested classes
      4. Delegation
        1. Implementation delegation
      5. Type checking
        1. Any
        2. Type casting
        3. Smart casting
    4. Understanding data classes
      1. Creating a data class
      2. Generated code
        1. equals()
        2. hashCode()
        3. toString()
        4. copy()
      3. Destructuring
    5. Working with enums, sealed classes, and objects
      1. Enums
      2. Sealed classes
      3. Object classes
        1. Singletons
        2. Companion objects
        3. Object expressions
    6. Summary
    7. Questions
    8. Further reading
  14. Section 3: Play Nice – Integrating Kotlin With Existing Code
  15. Interoperability as a Design Goal
    1. Technical requirements
    2. Understanding why Kotlin was designed with interop in mind
      1. Why is interop so important for Kotlin?
      2. How is interop achieved?
    3. Adding Kotlin to an existing Java project
      1. Adding Kotlin to an existing IntelliJ project
    4. Converting Java into Kotlin
      1. Converting Java files into Kotlin files
      2. Converting pasted Java code
    5. Summary
    6. Questions
  16. Crossing Over – Working across Java and Kotlin
    1. Technical requirements
    2. Working with Kotlin from Java
      1. Basic interop
        1. Creating class instances across languages
        2. Inheritance across languages
      2. Property access
      3. Handling null
      4. Function arguments
      5. Lack of static
    3. Working with Java from Kotlin
      1. Using existing code
      2. Enforcing null safety
    4. Embracing Kotlin idioms
      1. Goodbye helpers – embracing top-level and extension functions and properties
        1. Top-level functions
        2. Extension functions
        3. Top-level properties
          1. Top-level constant properties
          2. Top-level mutable properties
      2. Companion objects
    5. Are two languages better than one?
      1. Project structure
      2. Increased build size and speed
        1. Annotation processing
      3. Performance
      4. Complexity
    6. Summary
    7. Questions
    8. Further reading
  17. Controlling the Story
    1. Technical requirements
    2. Improving generated class names
      1. How are class names generated?
      2. Renaming the generated class
        1. Renaming a generated class name for top-level functions
        2. Renaming a generated class name for top-level properties
    3. Leveraging default values in Java
    4. Better companions
      1. How do companion objects work?
      2. When should we use a companion object?
      3. Modifying companion object names
    5. Bringing static to Kotlin
      1. Where can we use JvmStatic?
        1. @JvmStatic properties
        2. @JvmStatic methods
      2. When should we use the @JvmStatic annotation?
    6. Use-site annotation targets
      1. What are use-site targets?
      2. Specifying a use-site target
      3. Default targets
    7. Summary
    8. Questions
    9. Further reading
  18. Baby Steps – Integration through Testing
    1. Technical requirements
    2. Test-first integration
      1. Feature integration
        1. Advantages
        2. Disadvantages
      2. Test integration
        1. Advantages
        2. Disadvantages
      3. General impact of integration
    3. Testing interop
      1. Exercising your Kotlin code
        1. Testing closed classes
          1. Using Mockito
          2. Using the compiler plugin
      2. Exercising Java code from Kotlin
      3. Exercising Kotlin code from Java
    4. Improved testing with Kotlin
      1. The kotlin.test library
        1. Annotations
        2. Helper functions
      2. Mockito-Kotlin
    5. Summary
    6. Questions
    7. Further reading
  19. Section 4: Go Beyond – Exploring Advanced and Experimental Language Features
  20. Practical Concurrency
    1. Technical requirements
    2. Understanding async patterns
      1. Threading primitives
        1. Thread
        2. ExecutorService
      2. Advanced threading
        1. CompletableFuture
        2. RxJava
        3. Coroutines
    3. The foundations of coroutines
      1. What are coroutines?
      2. Coroutines with Kotlin
    4. Coroutines in practice
      1. Coroutine primitives
        1. Coroutine scopes
        2. Coroutine builders
        3. Suspending functions
      2. Working with blocking code
      3. Fetching data
    5. Summary
    6. Questions
    7. Further reading
  21. Building Your Own Tools – Domain-Specific Languages (DSLs)
    1. Technical requirements
    2. What is a DSL?
      1. Domain-specific languages
      2. Where are DSLs used?
        1. HTML
        2. Testing
        3. Dependency injection
    3. The building blocks of a DSL in Kotlin
      1. Top-level and extension functions
        1. Top-level functions
        2. Extension functions
      2. Function types with receivers
      3. Scope control
    4. Creating your first Kotlin DSL
      1. What problem are you trying to solve?
      2. Creating your starting point
      3. Adding elements
        1. Adding sodas
        2. Adding pizzas
      4. Making it easy to use
    5. Summary
    6. Questions
    7. Further reading
  22. Fully Functional – Embracing Functional Programming
    1. Technical requirements
    2. Understanding functional programming
      1. Pure functions
        1. Immutability
        2. Limited side effects
      2. Reduced complexity
    3. Understanding advanced functions
      1. Working with functional types
        1. Functional variables
        2. Functional arguments
      2. Improving the performance of higher-order functions
        1. The inline modifier
        2. The noinline modifier
    4. Leveraging the standard library
      1. Manipulating collections
        1. Filtering
        2. Mapping
        3. Associating
        4. Searching
      2. Exploring other useful functions
    5. Functional programming with Arrow
      1. What is Arrow?
        1. Typeclasses
        2. Data types
        3. Effects
    6. Summary
    7. Questions
    8. Further reading
  23. Section 5: The Wide World of Kotlin – Using Kotlin across the Entire Development Stack
  24. Kotlin on Android
    1. Technical requirements
    2. First class Kotlin for Android
      1. Adopting Kotlin for Android
      2. Kotlin first
      3. The future of Android
    3. Hello Android Kotlin
      1. Creating an Android app with Kotlin support
      2. Taking advantage of Kotlin on Android
        1. Configuring a view reference
        2. Responding to click events
        3. Creating factory methods for activities and fragments
        4. Handling savedInstanceState
    4. Building with Kotlin
      1. The Gradle Kotlin DSL
      2. Migrating to the Kotlin buildscript
      3. Simplifying dependency management with Kotlin
    5. First-party tooling
      1. Exploring Android KTX
        1. Adding Core KTX to your project
        2. Using Core KTX
        3. Using Fragment KTX
      2. Using Kotlin Android Extensions
        1. Binding views with Kotlin Android Extensions
        2. Generating Parcelable implementations
    6. Summary
    7. Questions
    8. Further reading
  25. Kotlin and Web Development
    1. Technical requirements
    2. Kotlin for the web
      1. Compiling Kotlin to JavaScript
        1. Transpiling to JavaScript
        2. Targeting JavaScript
      2. Using the compiled JavaScript
      3. Targeting JavaScript with Kotlin
    3. Building a Hello Kotlin project
      1. Creating a Kotlin project with a JavaScript target
      2. Writing Hello World for Kotlin JavaScript
      3. Examining the compiled JavaScript
      4. Consuming Kotlin through compiled JavaScript
    4. Integrating with existing JavaScript
      1. Working with other JavaScript frameworks
      2. Manipulating the DOM via Kotlin
    5. Summary
    6. Questions
    7. Further reading
  26. Introducing Multiplatform Kotlin
    1. Technical requirements
    2. Introducing Kotlin multiplatform
      1. Understanding how Kotlin approaches multiplatform
        1. Understanding the value of Kotlin multiplatform
        2. Targeting multiple platforms
      2. Differentiating Kotlin multiplatform
        1. Sharing logic, not UI
        2. Limiting risk
    3. Creating your first Kotlin multiplatform project
      1. Creating a shared module
      2. Adding an Android app
      3. Adding an iOS app
      4. Adding a web page
    4. Building a Kotlin multiplatform project
      1. Writing multiplatform Kotlin
      2. Leveraging multiplatform libraries
    5. Understanding the limitations of Kotlin multiplatform
      1. Understanding operational requirements
      2. Understanding Kotlin multiplatform ecosystem limitations
      3. Understanding framework and tooling limitations
    6. Summary
    7. Questions
    8. Further reading
  27. Taming the Monolith with Microservices
    1. Technical requirements
    2. Understanding microservices
      1. Exploring the limits of the monolith
      2. Embracing microservices
    3. Writing microservices with Kotlin
      1. Understanding Kotlin's relation to microservices
      2. Choosing Kotlin for your microservices
    4. Deploying your first Kotlin microservice
      1. Creating a Ktor project
      2. Writing a simple microservice
        1. Adding a route
      3. Deploying our microservice
        1. Deploying Kotlin services in production
        2. Deploying local Ktor services
      4. Scaling our routes
        1. Defining routes with extension functions
        2. Installing additional routes
    5. Summary
    6. Questions
    7. Further reading
  28. Practical Design Patterns
    1. Technical requirements
    2. Understanding design patterns
    3. Revisiting the Singleton pattern in Kotlin
      1. Understanding the Singleton pattern
      2. Implementing the Singleton pattern in Kotlin
    4. Revisiting the Factory pattern in Kotlin
      1. Understanding the Factory pattern
      2. Implementing the Factory pattern in Kotlin
    5. Revisiting the Builder pattern in Kotlin
      1. Understanding the Builder pattern
      2. Implementing the Builder pattern in Kotlin
    6. Revisiting the Strategy pattern in Kotlin
      1. Understanding the Strategy pattern
      2. Implementing the Strategy pattern in Kotlin
    7. Summary
    8. Questions
    9. Further reading
  29. Assessments
    1. Chapter 1: A New Challenger Approaches
    2. Chapter 2: Programmer's Multi-Tool
    3. Chapter 3: Understanding Programming Paradigms in Kotlin
    4. Chapter 4: First-Class Functions
    5. Chapter 5: Modeling Real-World Data
    6. Chapter 6: Interoperability by Design
    7. Chapter 7: Crossing Over – Working across Java and Kotlin
    8. Chapter 8: Controlling the Story
    9. Chapter 9: Baby Steps – Integration through Testing
    10. Chapter 10: Practical Concurrency
    11. Chapter 11: Building Your Own Tools – Domain-Specific Languages (DSLs)
    12. Chapter 12: Fully Functional – Embracing Functional Programming
    13. Chapter 13: Kotlin on Android
    14. Chapter 14: Kotlin and Web Development
    15. Chapter 15: Introducing Multiplatform Kotlin
    16. Chapter 16: Taming the Monolith with Microservices
    17. Chapter 17: Practical Design Patterns
  30. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Mastering Kotlin
  • Author(s): Nate Ebel
  • Release date: October 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781838555726