40,79 €
Learn how to apply Functional Programming with Kotlin to real-life projects with popular libraries like Arrow.
Functional programming makes your application faster, improves performance, and increases your productivity. Kotlin supports many of the popular and advanced functional features of functional languages. This book will cover the A-Z of functional programming in Kotlin. This book bridges the language gap for Kotlin developers by showing you how to create and consume functional constructs in Kotlin. We also bridge the domain gap by showing how functional constructs can be applied in business scenarios. We’ll take you through lambdas, pattern matching, immutability, and help you develop a deep understanding of the concepts and practices of functional programming. If you want learn to address problems using Recursion, Koltin has support for it as well. You’ll also learn how to use the funKtionale library to perform currying and lazy programming and more. Finally, you’ll learn functional design patterns and techniques that will make you a better programmer.By the end of the book, you will be more confident in your functional programming skills and will be able to apply them while programming in Kotlin.
Kotlin developers who have no functional programming experience, will benefit from this book.
Mario Arias is a software engineer and Spring certified instructor with more than 12 years of experience in software development and design, databases, training material design, and training delivery. He currently works as a software engineer in Manchester, UK, for Cake Solutions Ltd., a BAMTECH media company. Mario is well-known member of the Kotlin community and is part of the Arrow team, the group that developed and maintains the Arrow functional library. In his free time, he rides his bicycle and trains Brazilian Jiu-Jitsu. Rivu Chakraborty is a Caster.io instructor, Google Certified Android Developer, and senior tech member of Institute of Engineers (India). With more than 5 years of experience, he is currently working as a senior software engineer (Android) at Indus Net Technologies Pvt.Ltd. Rivu is a Kotlin and Android enthusiast and a Kotlin evangelist. He has been using Kotlin for more than 2 years. Rivu is the founder organizer of Kotlin Kolkata UG. He is also a core organizing team member of GDG Kolkata. Rivu has previously authored, Reactive Programming in Kotlin, and is working on two more books on Kotlin.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 353
Veröffentlichungsjahr: 2018
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 authors, 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: Aaron LazarAcquisition Editor: Sandeep MishraContent Development Editor: Zeeyan PinheiroTechnical Editor: Ruvika RaoCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Tejas Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Arvindkumar Gupta
First published: February 2018
Production reference: 1220218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78847-648-5
www.packtpub.com
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.
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
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.
Mario Arias is a software engineer and Spring certified instructor with more than 12 years of experience in software development and design, databases, training material design, and training delivery. He currently works as a software engineer in Manchester, UK, for Cake Solutions Ltd., a BAMTECH media company.
Mario is well-known member of the Kotlin community and is part of the Arrow team, the group that developed and maintains the Arrow functional library. In his free time, he rides his bicycle and trains Brazilian Jiu-Jitsu.
Rivu Chakraborty is a Caster.io instructor, Google Certified Android Developer, and senior tech member of Institute of Engineers (India). With more than 5 years of experience, he is currently working as a senior software engineer (Android) at Indus Net Technologies Pvt. Ltd.
Rivu is a Kotlin and Android enthusiast and a Kotlin evangelist. He has been using Kotlin for more than 2 years. Rivu is the founder organizer of Kotlin Kolkata UG. He is also a core organizing team member of GDG Kolkata. Rivu has previously authored, Reactive Programming in Kotlin, and is working on two more books on Kotlin.
Ganesh Samarthyam is a co-founder of CodeOps Technologies, a software technology, consultancy, and training company based in Bangalore. He has 16 years of experience in the IT industry, and his latest book, Refactoring for Software Design Smells: Managing Technical Debt by Morgan Kaufmann/Elsevier, has been translated to languages like Korean and Chinese. Ganesh loves exploring anything and everything about technology in his free time.
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.
Title Page
Copyright and Credits
Functional Kotlin
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the authors
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
Download the color images
Conventions used
Get in touch
Reviews
Kotlin – Data Types, Objects, and Classes
Classes
Properties
Methods
Inheritance
Abstract classes
Interfaces
Objects
Object declarations
Companion objects
Generics
Type alias
Nullable types
Checking for null
Checking for non-null types
Safe calls
The Elvis (?:) operator
The (!!) operator
Kotlin's type system
The Any type
Minimum common types
The Unit type
The Nothing type
Other types
Data classes
Canonical methods
The copy() method
Destructuring methods
Annotations
Enum
Summary
Getting Started with Functional Programming
What is functional programming?
Basics concepts
First-class and higher-order functions
Pure functions
Recursive functions
Lazy evaluation
Functional collections
Implementing a functional list
Summary
Immutability - It's Important
What is immutability?
Implementing immutability in Kotlin
The difference between var and val
Compile time constants
Types of immutability
Immutable reference  (referential immutability)
Immutable values
Immutable collections
The advantages of immutability
Thread safety
Low coupling
Referential transparency
Failure atomicity
Caching
Compiler optimization
Pure functions
The disadvantages of immutability
Summary
Functions, Function Types, and Side Effects
Functions in Kotlin
Returning two values from a function
Extension functions
Default arguments
Nested functions
Function types in functional programming
Lambda
Function as property
High order functions
Pure functions and side effects
Side effects
Pure functions
Summary
More on Functions
Single-expression functions
Parameters
vararg
Lambda
Named parameters
Named parameters on high-order functions
Default parameters
Extension functions
Extension functions and inheritance
Extension functions as members
Extension functions with conflicting names
Extension functions for objects
Infix functions
Operator overloading
Binary operators
Invoke
Indexed access
Unary operators
Type-safe builders
Creating a DSL
Inline functions
Inline restrictions
Recursion and corecursion
Summary
Delegates in Kotlin
Introduction to delegation
Understanding delegation
Delegates in Kotlin
Property delegation (standard delegates)
The Delegates.notNull function and lateinit
The lazy function
Observing property value change with Delegates.Observable
The power of veto – Delegates.vetoable
Delegated map
Custom delegation
Local delegates
Class delegation
Summary
Asynchronous Programming with Coroutines
Introduction to coroutines
Understanding JVM threads
Hello, coroutine world!
Using coroutines in real life
Synchronous implementation
Callbacks
Java Futures
Promises with Kovenant 
Coroutines
Coroutine context
Channels
Channel pipelines
Managing mutable state
Switching contexts
Thread safe structures
Mutexes
Actors
Summary
Collections and Data Operations in Kotlin
An introduction to collections
The advantages of a collections framework
List and MutableList
Set and MutableSet
Map and MutableMap
Data operations in a collection
The map function
The filter function
The flatMap function
The drop functions
The take functions
The zip function
Grouping collections
Summary
Functional Programming and Reactive Programming
Combining FP with OOP
Functional reactive programming
The Reactive Manifesto
Functional reactive frameworks for Kotlin
Getting started with RxKotlin
Downloading and setting up RxKotlin
Comparing the Pull mechanism with the RxJava Push mechanism
Observables
How Observable works
The Observable.create method
The Observable.from methods
Iterator<T>.toObservable
Subscriber – the Observer interface
Subscribing and disposing
Summary
Functors, Applicatives, and Monads
Functors   
Monads
Applicatives
Summary
Working with Streams in Kotlin
Introduction to Streams
Collections versus Streams
Working with Streams
Primitive streams
Stream factory methods
Stream Builder
Creating empty Streams – Stream.empty()
Creating a Stream by passing elements – Stream.of()
Generating Streams – Stream.generate()
Collector and Stream.collect – collecting Streams
The Collectors.toList(), Collectors.toSet(), and Collectors.toCollection() methods
Collecting into Map – Collectors.toMap()
Joining Stream of strings – Collectors.joining()
Grouping elements of Stream – Collectors.groupingBy()
Summary
Getting Started with Arrow
Function composition
Partial application
Binding
Reverse
Pipes
Currying
Differences between the currying and partial application
Logical complement
Memoization
Partial functions
Identity and constant
Optics
Configuring Arrows code generation
Generating lenses
Summary
Arrow Types
Option
Arrow's type hierarchy
Either
Monad transformers
Try
State
Corecursion with State
Summary
Kotlin's Quick Start
Writing and running Kotlin
Kotlin online
On your console
Installing SDKMAN
Installing Kotlin through SDKMAN
Kotlin's REPL
Compiling and executing Kotlin files
Using Gradle
Install Gradle through SDKMAN
Creating a distributable Gradle command
Creating a Gradle project file
Creating our Hello World code
Using IntelliJ IDEA or Android Studio
Importing Gradle files with IntelliJ IDEA
Basic Kotlin syntax
General features
Packages
String concatenation and interpolation
Comments 
Control structures
if expression
when expression
for loop
while and do loops
Going further
Other Books You May Enjoy
Leave a review - let other readers know what you think
With Google's announcement at the I/O Conference in 2017 to make Kotlin an official language for Android, Kotlin has been gaining popularity among developers around the world.
However, Kotlin's use and popularity aren't limited to the Android community. Many other communities, such as the desktop, web, and backend community are embracing Kotlin too. Many new libraries and frameworks are being created and existing ones are providing support for Kotlin.
With more developers coming to the Kotlin community and with its natural flexibility, more programming styles are being tried. The purpose of this book is to introduce the functional programming style to the wide Kotlin community, leading and guiding on the first steps, and giving the basic tools to progress further to more advanced concepts.
This book is for Kotlin users (programmers, engineers, library authors, and architects) who have a basic understanding of Kotlin and want to understand the basics ideas behind functional programming and how to use it in a practical way (if you're entirely new to Kotlin, our Appendix, Kotlin's Quick Start will give you a quick start with the language).
Chapter 1, Kotlin - Data Types, Objects, and Classes, introduces you to object-oriented programming in Kotlin. Kotlin is primary object-oriented programming, and we'll use these features to introduce a functional programming style.
Chapter 2, Getting Started with Functional Programming, covers the basic principles of functional programming using Kotlin's object-oriented programming features.
Chapter 3, Immutability - It's Important, emphasizes on immutability as one of the most important concepts in functional programming. This chapter will give you an in-depth understanding of immutability.
Chapter 4, Functions, Function Types, and Side Effects, introduces you to the basic functional programming concepts around functions, pure functions, and various function types and side effects.
Chapter 5, More on Functions, talks about Kotlin's features for functional programming such as extension functions, operator overloading, DSLs, and corecursion.
Chapter 6, Delegates in Kotlin, covers how Kotlin has language-level support for delegates. Though delegates are a object-oriented programming concept, they can be helpful in making your code more modular.
Chapter 7, Asynchronous Programming with Coroutines, gives you an introduction to asynchronous programming in Kotlin, comparing different styles against coroutines.
Chapter 8, Collections and Data Operations in Kotlin, covers the enhanced collections API by Kotlin and the functional interfaces that Kotlin's collections framework has to offer.
Chapter 9, Functional Programming and Reactive Programming, shows how functional programming can be combined with other programming paradigms to get the best out of them. This chapter discusses how you can combine functional programming with object-oriented programming and reactive programming.
Chapter 10, Functors, Applicatives and Monads, gives you an introduction to typed functional programming and its basic concepts. It also talks about how to implement it in Kotlin.
Chapter 11, Working with Streams in Kotlin, gets you introduced to the Streams API in Kotlin.
Chapter 12, Getting Started with Arrow, covers how to use Arrow and its extensions for functional programming, function composition, currying, partial application, memoization, and optics.
Chapter 13, Arrow Types, helps you understand Arrow data types such as Option, Either, Try, and State and its type classes, functors, and monads.
Appendix, Kotlin's Quick Start, it provides everything that you need to start writing a Kotlin code, such as tools, basic syntax constructs and other resources to help you progress in your Kotlin journey.
The only recommended software to run and write Kotlin programs is IntelliJ IDEA (there are other ways to do it, and we cover them in the Appendix, Kotlin's Quick Start).
You can download IntelliJ IDEA from https://www.jetbrains.com/idea/download/.
You can install IntelliJ IDEA on Windows, Mac, and Linux:
For Windows
: You can use any Windows version from XP to 10. To install it on Windows, run the installer executable and follow the instructions.
For Mac
: You can use any macOS version starting from 10.8. To install it on macOS, mount the disk image file and copy
IntelliJ IDEA.app
60
to your
Application
folder.
For Linux
: You can use any GNOME or KDE desktop. To install it Linux unpack the
tar.gz
file using the
tar -xzf idea-*.tar.gz
command and run the
idea.sh
from the
bin
subdirectory.
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/Functional-Kotlin. 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 athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/FunctionalKotlin_ColorImages.pdf .
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.
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
In this chapter, we'll cover Kotlin's type system, object-oriented programming (OOP) with Kotlin, modifiers, destructuring declarations, and more.
Kotlin is, primarily, an OOP language with some functional features. When we use OOP languages to resolve problems, we try to model the objects that are a part of our problem in an abstract way with the information that is relevant to the problem.
If we're designing an HR module for our company, we'll model employees with state or data (name, date of birth, social security number, and others) and behavior (pay salary, transfer to another division, and others). Because a person can be very complex, there is information that isn't relevant for our problem or domain. For example, the employee's favorite style of bicycle isn't relevant for our HR system, but it is very relevant for an online cycling shop.
Once we identify the objects (with data and behavior) and the relationship with other objects of our domain, we can start developing and writing the code that we'll make a part of our software solution. We'll use language constructs (construct is a fancy way to say allowed syntax) to write the objects, categories, relationships, and so on.
Kotlin has many constructs that we can use to write our programs and, in this chapter, we'll cover many of those constructs, such as:
Classes
Inheritance
Abstract classes
Interfaces
Objects
Generics
Type alias
Null types
Kotlin's type system
Other types
This section is just a short introduction to generics; later, we'll cover it in detail.
Generic programming is a style programming that focuses on creating algorithms (and collaterally, data structures) that work on general problems.
The Kotlin way to support generic programming is using type parameters. In a few words, we wrote our code with type parameters and, later on, we pass those types as parameters when we use them.
Let's take, for example, our Oven interface:
interface Oven { fun process(product: Bakeable)}
An oven is a machine, so we could generalize it more:
interface Machine<T> { fun process(product: T)}
The Machine<T> interface defines a type parameter T and a method process(T).
Now, we can extend it with Oven:
interface Oven: Machine<Bakeable>
Now, Oven is extending Machine with the Bakeable type parameter, so the process method now takes Bakeable as a parameter.
Type alias
