Book Image

Kotlin Standard Library Cookbook

By : Samuel Urbanowicz
Book Image

Kotlin Standard Library Cookbook

By: Samuel Urbanowicz

Overview of this book

For developers who prefer a more simplistic approach to coding, Kotlin has emerged as a valuable solution for effective software development. The Kotlin standard library provides vital tools that make day-to-day Kotlin programming easier. This library features core attributes of the language, such as algorithmic problems, design patterns, data processing, and working with files and data streams. With a recipe-based approach, this book features coding solutions that you can readily execute. Through the book, you’ll encounter a variety of interesting topics related to data processing, I/O operations, and collections transformation. You’ll get started by exploring the most effective design patterns in Kotlin and understand how coroutines add new features to JavaScript. As you progress, you'll learn how to implement clean, reusable functions and scalable interfaces containing default implementations. Toward the concluding chapters, you’ll discover recipes on functional programming concepts, such as lambdas, monads, functors, and Kotlin scoping functions, which will help you tackle a range of real-life coding problems. By the end of this book, you'll be equipped with the expertise you need to address a range of challenges that Kotlin developers face by implementing easy-to-follow solutions.
Table of Contents (11 chapters)

Folding and reducing data sets

While the map() operator takes a list of a given size and returns another list of the same size and of the modified type, the fold() and reduce() operations applied to the data set return a single element, composed of the consecutive elements of the data set. This may sound like a simple scenario for using a plain, imperative-style loop and local accumulator variable that holds a current state and is updated at each iteration. We can consider the simple task of summing up integer values. Let's consider that we want to compute a sum of consecutive integers from 0 to 10. We could achieve it using a simple for loop:

var sum = 0
(1..10).forEach {
sum += it
}

However, there is an alternative, functional way of performing such computations, using the fold() function:

val sum = (1..3).toList().fold(0) { acc, i -> acc + i }

The second approach is...