Kotlin Standard Library Cookbook - Samuel Urbanowicz - E-Book

Kotlin Standard Library Cookbook E-Book

Samuel Urbanowicz

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build optimized applications in Kotlin by learning how to make use of the standard library features the smart way




Key Features



  • Get the most out of the Kotlin library to develop high-quality portable applications


  • Explore the powerful support for data processing and I/O operations


  • Discover ways to enhance your Android application development





Book Description



Given the verbosity of Java, developers have turned to Kotlin for effective software development. The Kotlin standard library provides vital tools that make day-to-day Kotlin programming easier. This library features the core attributes of the language, such as algorithmic problems, design patterns, data processing, and working with files and data streams.






The recipes in this book offer coding solutions that can be readily executed. The book covers various topics related to data processing, I/O operations, and collections transformation. We'll walk through effective design patterns in Kotlin and you'll understand how coroutines add new features to JavaScript.







As you make your way through the chapters, you'll learn how to implement clean, reusable functions and scalable interfaces containing default implementations. In the concluding chapters, we'll provide recipes on functional programming concepts, such as lambdas, monads, functors, and Kotlin scoping functions.







By the end of the book, you'll be able to address a range of problems that Kotlin developers face by implementing easy-to-follow solutions.





What you will learn



  • Work with ranges, progressions, and sequences in use cases


  • Add new functionalities to current classes with Kotlin extensions


  • Understand elements such as lambdas, closures, and monads


  • Build a REST API consumer with Retrofit and a coroutine adapter


  • Discover useful tips and solutions for making your Android projects


  • Explore the benefits of standard library features



Who this book is for



This book is for software developers who are familiar with Kotlin's basics and want to discover more advanced features and concepts, especially those provided by the Kotlin standard library. It's also ideal for experienced software developers who are familiar with the functional programming paradigm and other programming languages who want to switch to Kotlin. It will also help Java developers switch to Kotlin and integrate it into existing Java Virtual Machine (JVM) projects.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 251

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Kotlin Standard Library Cookbook

 

 

Master the powerful Kotlin standard library through practical code examples

 

 

 

 

 

 

 

 

 

 

 

Samuel Urbanowicz

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Kotlin Standard Library Cookbook

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Richa TripathiAcquisition Editor: Chaitanya NairContent Development Editor: Akshada IyerTechnical Editor: Abhishek SharmaCopy Editor:Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jisha ChirayilProduction Coordinator: Aparna Bhagat

First published: July 2018

Production reference: 1260718

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-766-8

www.packtpub.com

"I have no special talent. I am only passionately curious."                                                                                         - A. Einstein I dedicate the book to all curious souls… most of all to you, Agat.
 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Samuel Urbanowicz is an experienced software engineer skilled in mobile applications and backend development. A fan of modern programming languages, he has been using Kotlin since its beginning. He's always curious to dive into technologies. He is especially passionate about machine learning. Samuel believes that the Kotlin language has great potential for multiplatform development. He has work experience in both big corps and small start-ups. He is an active contributor to open source projects.

I would like to thank the mentors who inspired me along my programming adventures. I wouldn't have the same passion for programming if not for the wisdom I learned from you: "Coding must be fun, otherwise we are doing it wrong!". I am also grateful to the reviewers who made the book better. This book could not have been written without you.

About the reviewer

Miłosz Pacholczyk is a software developer with 5 years of commercial experience in Java. He worked on B2B software used by leading manufacturers of automotive and construction industries. He graduated from the University of Warsaw.

 

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Kotlin Standard Library Cookbook

Dedication

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Get in touch

Reviews

Ranges, Progressions, and Sequences

Introduction

Exploring the use of range expressions to iterate through alphabet characters

Getting ready

How to do it...

How it works...

There's more...

See also

Traversing through ranges using progression with a custom step value

Getting ready

How to do it...

How it works...

See also

Building custom progressions to traverse dates

Getting ready

How to do it...

How it works...

Using range expressions with flow control statements

Getting ready

How to do it...

How it works...

There's more...

See also

Discovering the concept of sequences

Getting ready

How to do it...

How it works...

There's more...

See also

Applying sequences to solve algorithmic problems

Getting ready

How to do it...

How it works...

Expressive Functions and Adjustable Interfaces

Introduction

Declaring adjustable functions with default parameters

How to do it...

How it works...

See also

Declaring interfaces containing default implementations

Getting ready

How to do it...

How it works...

There's more...

See also

Extending functionalities of classes

Getting ready

How to do it...

How it works...

There's more...

Destructuring types

Getting ready

How to do it...

How it works...

There's more...

Returning multiple data

How to do it...

How it works...

There's more...

See also

Inlining parameters of closure type

Getting ready

How to do it...

How it works...

There's more...

Infix notations for functions

Getting ready

How to do it...

How it works...

There's more...

See also

Smart types checking with generic reified parameters

Getting ready

How to do it...

How it works...

Overloading operators

Getting ready

How to do it...

How it works...

There's more...

Shaping Code with Kotlin Functional Programming Features

Introduction

Working effectively with lambda expressions

Getting ready

How to do it...

How it works...

There's more...

Discovering basic scoping functions – let, also, apply

Getting ready

How to do it...

How it works...

See also

Initializing objects the clean way using the run scoping function

Getting ready

How to do it...

How it works...

There's more...

See also

Working with higher-order functions

How to do it...

How it works...

Functions currying 

Getting ready

How to do it...

How it works...

There's more...

Function composition

Getting ready

How to do it...

How it works...

Implementing the Either Monad design pattern

How to do it...

How it works...

There's more...

Approach to automatic functions memoization 

How to do it...

How it works...

There's more...

Powerful Data Processing

Introduction

Composing and consuming collections the easy way

Getting ready

How to do it...

How it works...

There's more...

See also

Filtering datasets

Getting ready

How to do it...

How it works...

There's more...

See also

Automatic null removal

How to do it...

How it works...

See also

Sorting data with custom comparators

Getting started

How to do it...

How it works...

There's more...

Building strings based on dataset elements

How to do it...

How it works...

There's more...

See also

Dividing data into subsets

Getting ready

How to do it...

How it works...

There's more...

See also

Data transformation with map and flatMap

How to do it...

How it works...

There's more...

Folding and reducing data sets

How to do it...

How it works...

There's more...

Grouping data

How to do it...

How it works...

There's more...

See also

Tasteful Design Patterns Adopting Kotlin Concepts

Introduction

Implementing the Strategy pattern

How to do it...

How it works...

There's more...

See also

Exploring the power of the Delegation pattern

Getting ready

How to do it...

How it works...

See also

Implementing delegated class properties

Getting ready

How to do it...

How it works...

There's more...

See also

Tracking state with the Observer pattern

How to do it...

How it works...

See also

Restricting property updates with the Vetoable delegate

How to do it...

How it works...

See also

Implementing the advanced Observer pattern by defining a custom property delegate

How to do it...

How it works...

See also

Working with the Lazy delegate

How to do it...

How it works...

See also

Implementing builders the smart way

Getting ready

How to do it...

How it works...

There's more...

See also

Friendly I/O Operations

Introduction

Reading the contents of a file

Getting ready

How to do it...

How it works...

See also

Ensuring stream closing with the use function

Getting ready

How to do it...

How it works...

Reading the contents of a file line by line

Getting ready

How to do it...

How it works...

See also

Writing the contents to a file

How to do it...

How it works...

See also

Appending a file

How to do it...

How it works...

Easy file copying

Getting ready

How to do it...

How it works...

Traversing files in a directory

Getting ready

How to do it...

How it works...

Making Asynchronous Programming Great Again

Introduction

Executing tasks in the background using threads

Getting ready

How to do it...

How it works...

See also

Background threads synchronization

Getting ready

How to do it...

How it works...

See also

Using coroutines for asynchronous, concurrent execution of tasks

Getting ready

How to do it...

How it works...

See also

Using coroutines for asynchronous, concurrent tasks execution with results handling

Getting ready

How to do it...

How it works...

There's more...

See also

Applying coroutines for asynchronous data processing

How to do it...

How it works...

See also

Easy coroutine cancelation

Getting ready

How to do it...

How it works...

See also

Building a REST API client with Retrofit and a coroutines adapter

Getting ready

How to do it...

How it works...

See also

Wrapping third-party callback-style APIs with coroutines

Getting ready

How to do it...

How it works...

See also

Best Practices for the Android, JUnit, and JVM UI Frameworks

Introduction

Clean and safe view-binding with the Android Extensions plugin

Getting ready

How to do it...

How it works...

There's more...

Applying coroutines for asynchronous UI programming on Android, JavaFX, and Swing

Getting ready

How to do it...

How it works...

There's more...

See also

Easy class serialization on Android using the @Parcelize annotation

Getting ready

How to do it...

How it works...

See also

Implementing a custom property delegate that provides lifecycle-aware values

Getting ready

How to do it...

How it works...

See also

Easy operations on SharedPreferences

Getting ready

How to do it...

How it works...

See also

Less boilerplate Cursor data parsing

Getting ready

How to do it...

How it works...

Mocking dependencies with the Mockito Kotlin library

Getting ready

How to do it...

How it works...

See also

Verifying function invocations

Getting ready

How to do it...

How it works...

Unit tests for Kotlin coroutines

Getting ready

How to do it...

How it works...

Miscellaneous

Introduction

Kotlin and Java interoperability

How to do it...

How it works...

Kotlin and JavaScript interoperability

Getting ready

How to do it...

How it works...

There's more...

Renaming generated functions

How to do it...

How it works...

There's more...

See also

Decompiling Kotlin code to Java and JVM bytecode

Getting ready

How to do it...

How it works...

Adding custom names for imports

How to do it...

How it works...

Wrapping complex type declarations with type aliases

Getting ready

How to do it...

How it works...

Expressive try…catch declarations

Getting ready

How to do it...

How it works...

There's more...

Safe type-casting 

How to do it...

How it works...

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

The primary aim of Kotlin Standard Library Cookbook is to help you dive into advanced language concepts and features as fast as possible in a friendly way. It covers a wide range of general programming problems at varying difficulty levels, including design patterns, functional programming, data processing, and more. The book consists of recipes that present a specific problem and give a step-by-step explanation of how to approach it effectively. All the presented features of the standard library are well explained, allowing you to discover them with ease.

This book will help software developers switch to Kotlin with ease and integrate it seamlessly into the existing JVM and JavaScript projects. Examples included in the book can easily be implemented in your own projects. You can also get the ready-made solutions from the book's GitHub repository if you prefer to follow and test the recipes in your favorite IDE. Once you have completed the book, you should have expert knowledge and insight into the language's advanced concepts, allowing you to address your daily programming challenges efficiently.

Who this book is for

The book is ideal for those who are already familiar with the basics of Kotlin and want to discover how to effectively solve day-to-day programming problems with state-of-the-art solutions, utilizing advanced language and standard library features. Experienced programmers who are willing to switch to Kotlin from other languages, especially Java, Scala, and JavaScript, will find it helpful as well.

What this book covers

Chapter 1, Ranges, Progressions, and Sequences, presents the concept of Kotlin ranges and sequences. It shows how to approach common algorithmic problems by defining custom sequences and how to define ranges for custom classes.

Chapter 2, Expressive Functions and Adjustable Interfaces, shows how to approach designing functions and interfaces using the language's built-in features. The chapter explains how to implement clean, reusable functions, and scalable interfaces containing default implementations. The recipes also cover other features of the language, such as inlining closures, destructuring variables, reified type parameters, and other useful tips that help design more flexible and natural code.

Chapter 3, Shaping Code with Kotlin Functional Programming Features, shows how to solve real-life programming challenges by adopting state-of-the-art functional programming patterns. The chapter helps readers get familiar with Kotlin support for functional programming concepts provided by the standard library and the built-in language features.

Chapter 4, Powerful Data Processing, focuses on presenting standard library support for declarative style operations on collections. The included recipes present solutions to varying programming problems related to dataset transformations, reducing, or filtering. The chapter shows how to approach data processing operations practicing a functional programming style with the use of powerful functionalities built into the standard library.

Chapter 5, Tasteful Design Patterns Adopting Kotlin Concepts, presents the Kotlin-specific approach to implementing popular design patterns, including the Observer and Lazy delegates, Builder, Strategy, and more. Design patterns presented in the following chapter are backed by real-life examples that emphasize the benefits of the Delegation pattern.

Chapter 6, Friendly I/O Operations, presents useful extension functions available in the standard library that simplify the work with I/O operations. The chapter focuses on common use cases of read-write operations on files, working with streams and buffers, and the Kotlin approach to traversing files available in a specific directory.

Chapter 7, Making Asynchronous Programming Great Again, is an in-depth guide to asynchronous programming focusing on the Kotlin coroutines framework and its application in real-life situations. The chapter presents how to optimize and advance previous examples by executing parts of their code in the background in a non-blocking way. Here, you will also find a practical example of implementing an asynchronous REST client with the Retrofit library and the coroutines framework.

Chapter 8, Best Practices for the Android, JUnit, and JVM UI Frameworks, covers practical problems specific to the popular frameworks, among which Kotlin is the one used most often. In general, it will focus on Android platform-specific aspects and asynchronous UI programming with coroutines, both on Android and JVM frameworks such as JavaFX and Swing. It will also help you to write effective unit tests for the JVM platform using the JUnit framework. The recipes related to unit testing will also include more advanced topics, such as mocking dependencies with the Mockito Kotlin library and testing asynchronous code based on the coroutines framework.

Chapter 9, Miscellaneous, presents handy solutions to various problems and issues that Kotlin developers deal with on a daily basis.

To get the most out of this book

In order to learn from the book efficiently, you should follow the included recipes step by step and try to implement the solutions on your own. You can download the sample code from the book's GitHub repository athttps://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook and import it into IntelliJ IDEA and Android Studio. If you have any trouble, you can run and test each recipe instantly in the IDE.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Ranges, Progressions, and Sequences

In this chapter, we will cover the following recipes:

Exploring the use of range expressions to iterate through alphabet characters

Traversing 

through ranges using progression with a custom step value

Building custom progressions to traverse dates

Using range expressions with flow control statements

Discovering the concept of sequences

Applying sequences to solve algorithmic problems

Introduction

This chapter will focus on explaining the advantages of range expressions and sequences. These powerful data structure concepts offered by the Kotlin standard library can help you to improve the quality and readability of your code, as well as its safety and performance. Range expressions provide a declarative way of iterating through sets of comparable types using for loops. They are also useful for implementing concise and safe control flow statements and conditions. The Sequence class, as a missing supplement to the Collection type, provides a built-in lazy evaluation of its elements. In many cases, using sequences can help optimize data-processing operations and make the code more efficient in terms of computation complexity and memory consumption. The recipes covered in this chapter are going to focus on solving real-life programming problems. Moreover, at the same time, they are also going to explain how those concepts work under the hood.

Exploring the use of range expressions to iterate through alphabet characters

Ranges, provided by the Kotlin standard library, are a powerful solution for implementing iteration and conditional statements in a natural and safe way. A range can be understood as an abstract data type that represents a set of iterable elements and allows iteration through them in a declarative way. The ClosedRange interface from the kotlin.ranges package is a basic model of the range data structure. It contains references to the first and last elements of the range and provides the contains(value: T): Boolean and isEmpty(): Boolean functions, which are responsible for checking whether the specified element belongs to the range and whether the range is empty. In this recipe, we are going to learn how to declare a range that consists of alphabet characters and iterate through it in a decreasing order.

How to do it...

Declare a decreasing range of alphabet characters:

'Z' downTo 'A'

                2. Create a for loop to traverse the range:

for (letter in 'Z' downTo 'A') print(letter)

How it works...

As a result, we are going to get the following code printed out to the console:

ZYXWVUTSRQPONMLKJIHGFEDCBA

As you can see, there is also a downTo() extension function variant for the available Char type. We are using it to create a range of characters from Z to A. Note that, thanks for the infix notation, we can omit the brackets while invoking the function—'Z' downTo 'A'.

Next, we are creating a for loop, which iterates through the range and prints out the subsequent Char elements. Using the in operator, we are specifying the object that is being iterated in the loop—and that's it! As you can see, the Kotlin syntax for the for loop is neat and natural to use.

Implementations of ranges of the primitive types, such as IntRange, LongRange, and CharRange, also contain Iterator interface implementations under the hood. They are being used while traversing the range using the for loop under the hood. In fact, the range implementing the Iterable interface is called a progression. Under the hood, the IntRange, LongRange, and CharRange classes inherit from the IntProgression, LongProgression, and CharProgression base classes, and they provide the implementations of the Iterator interface internally.

See also