






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Sample programming book booklet pamphlet
Typology: Cheat Sheet
1 / 30
This page cannot be seen from the preview
Don't miss anything!























Second Edition
Scala is a hybrid language that mixes both the Object-Oriented Programming (OOP) and Functional Programming (FP) paradigms. This allows you to get up-and-running pretty quickly without knowing the language in detail. Over time, as you learn more, you are hopefully going to appreciate what makes Scala great: its functional building blocks.
Pattern matching, folds, recursion, higher-order functions, etc. If you decide to continue down this road, you will discover the functional subset of the community and its great ecosystem of libraries.
Sooner rather than later, you will come across the Cats^1 library and its remarkable documentation. You might even start using it in your projects! Once you get familiar with the power of typeclasses such as Functor, Monad, and Traverse, I am sure you will love it.
As you evolve into a functional programmer, you will learn about functional effects and referential transparency. You might as well start using the popular IO Monad present in Cats Effect^2 and other similar libraries.
One day you will need to process a lot of data that doesn’t fit into memory; a suitable solution to this engineering problem is streaming. While searching for a valuable can- didate, you might stumble upon a purely functional streaming library: Fs2^3. You will quickly learn that it is also a magnificent library for control flow.
A requirement to build a RESTful API^4 will more likely come down your way early on in your career. Http4s^5 leverages the power of Cats Effect and Fs2 so you can focus on shipping features while remaining on functional land.
You might decide to adopt a message broker as a communication protocol between microservices and to distribute data. You name it: Kafka, Pulsar, RabbitMQ, to mention a few. Each of these wonderful technologies has a library that can fulfill every client’s needs.
(^1) https://typelevel.org/cats (^2) https://typelevel.org/cats-effect (^3) https://fs2.io (^4) https://restfulapi.net/ (^5) https://http4s.org/
One can only dream of starting writing a book and making it over the finish line. Yet, I managed to do this twice! Though, this would have been an impossible task without the help of many people that had supported me over time, as well as many open-source and free software I consider indispensable.
I am beyond excited and can only be thankful to all of you.
People
I consider myself incredibly lucky to have had all these great human beings influencing the content of this book one way or another. This humble piece of work is dedicated:
Last but not least, this edition is dedicated to all the people that make the Typelevel ecosystem as great as it is nowadays, especially to the maintainers and contributors of my two favorite Scala libraries: Cats Effect and Fs2. This book wouldn’t exist without all of your work! #ScalaThankYou
Although the book was thoroughly reviewed, I am the sole responsible for all of the opinionated sentences, and any remaining mistakes are only mine.
(^1) https://twitter.com/impurepics
Acknowledgments
Fonts
This book’s main font is Latin Modern Roman^5 , distributed under The GUST Font License (GFL)^6. Other fonts in use are listed below.
(^5) https://tug.org/FontCatalogue/latinmodernroman/ (^6) https://www.ctan.org/license/gfl (^7) https://www.jetbrains.com/lp/mono/ (^8) https://github.com/JetBrains/JetBrainsMono/blob/master/OFL.txt (^9) https://sourceforge.net/projects/linuxlibertine/ (^10) https://opensource.org/licenses/gpl-2.0.php (^11) https://scripts.sil.org/cms/scripts/page.php?item_id=OFL
At the moment of writing, all the standalone examples use Scala 2.13.5 and sbt 1.5.3, as well as the following dependencies defined in this minimal build.sbt^1 file.
ThisBuild / scalaVersionႍ := "2.13.5"
lazy val root = (project in file(".")) .settings( nameႍ := "minimal", libraryDependenciesႍ ++= Seq( compilerPlugin( "org.typelevel" %% "kind-projector" % "0.12.0" cross CrossVersion.full ), "org.typelevel" %% "cats-core" % "2.6.1", "org.typelevel" %% "cats-effect" % "3.1.1", "org.typelevel" %% "cats-mtl" % "1.2.1", "co.fs2" %% "fs2-core" % "3.0.3", "dev.optics" %% "monocle-core" % "3.0.0", "dev.optics" %% "monocle-macro" % "3.0.0", "io.estatico" %% "newtype" % "0.4.4", "eu.timepit" %% "refined" % "0.9.25", "eu.timepit" %% "refined-cats" % "0.9.25", "tf.tofu" %% "derevo-cats" % "0.12.5", "tf.tofu" %% "derevo-cats-tagless" % "0.12.5", "tf.tofu" %% "derevo-circe-magnolia" % "0.12.5", "tf.tofu" %% "tofu-core-higher-kind" % "0.10.2" ), scalacOptionsႍ ++= Seq( "-Ymacro-annotations", "-Wconf:cat=unused:info" )
The sbt-tpolecat plugin is also necessary. Here is a minimal plugins.sbt file.
addSbtPlugin("io.github.davidgregory084" % "sbt-tpolecat" % "0.1.17")
(^1) https://gist.github.com/gvolpe/04b31a5caa875f8f16bcd1d12b72face
This book is considered intermediate to advanced. Familiarity with functional program- ming concepts and basic FP libraries such as Cats and Cats Effect will be of tremendous help even though I will do my best to be as clear and concise as I can.
Both Scala with Cats^1 and Essential Effects^2 , in that order, are excellent books to learn these concepts. The official documentation of Cats Effect^3 is also a great resource.
The following list details the topics required to understand this book.
Unfortunately, these topics are quite lengthy to be explained in this book, so readers are expected to be acquainted with them. However, some examples will be included, and this might be all you need.
If the requirements feel overwhelming, it is not because the entire book is difficult, but rather because some specific parts might be. You can try to read it, and if at some point you get stuck, you can skip that section. You could also make a pause, go to read about these resources, and then continue where you left off.
Remember that we are going to develop an application together, which will help you learn a lot, even if you haven’t employed these techniques and libraries before.
(^1) https://underscore.io/books/scala-with-cats/ (^2) https://essentialeffects.dev/ (^3) https://typelevel.org/cats-effect/ (^4) https://typelevel.org/blog/2016/08/21/hkts-moving-forward.html (^5) https://typelevel.org/cats/typeclasses.html (^6) https://typelevel.org/blog/2017/05/02/io-monad-for-cats.html (^7) https://en.wikipedia.org/wiki/Referential_transparency
For conciseness, most of the imports and some datatype definitions are elided from the book, so it is recommended to read it by following along the two Scala projects that supplement it.
The first project includes self-contained examples that demonstrate some features or techniques explained independently.
The latter contains the source code of the full-fledged application that we will develop in the next ten chapters, including a test suite and deployment instructions.
Bear in mind that the presented Shopping Cart application only acts as a guideline. To get a better learning experience, readers are encouraged to write their own application from scratch; getting your hands dirty is the best way to learn.
There is also a Gitter channel^3 where you are welcome to ask any kind of questions related to the book or functional programming in general.
(^1) https://github.com/gvolpe/pfps-examples (^2) https://github.com/gvolpe/pfps-shopping-cart (^3) https://gitter.im/pfp-scala/community
Before we get to analyzing the business requirements and writing the application, we are going to explore some design patterns and best practices. A few well-known; others not so standard and biased towards my preferences.
These will more likely appear at least once in the application we will develop, so you can think of this chapter as a preparation for what’s to come.
Strongly-typed functions
One of the most significant benefits of functional programming is that it lets us rea- son about functions by looking at their type signature. Yet, the truth is that these are commonly created by us, imperfect humans, who often end up with weakly-typed functions.
For instance, let’s look at the following function.
def lookup(username: String, email: String): F[Option[User]]
Do you see any problems with it? Let’s see how we can use it.
$ lookup("[email protected]", "aeinstein") $ lookup("aeinstein", "123") $ lookup("", "")
See the issue? It is not only easy to confuse the order of the parameters but it is also straightforward to feed our function with invalid data! So what can we do about it? We could make this better by introducing value classes.
In vanilla Scala, we can wrap a single field and extend the AnyVal abstract class to avoid some runtime costs. Here is how we can define value classes for username and email.
case class Username(val value: String) extends AnyVal case class Email(val value: String) extends AnyVal
Now we can re-define our function using these types.
def lookup(username: Username, email: Email): F[Option[User]]
Notice that we can no longer confuse the order of the parameters.
$ lookup(Username("aeinstein"), Email("[email protected]"))
Or can we?
$ lookup(Username("[email protected]"), Email("aeinstein")) $ lookup(Username("aeinstein"), Email("123")) $ lookup(Username(""), Email(""))
Fine, we are doing this on purpose. However, in a statically-typed language, we would expect the compiler to help prevent this but it cannot due to lack of information. A way to communicate our intentions to the compiler is to make the case class constructors private only expose smart constructors.