Building Applications with Scala - Diego Pacheco - E-Book

Building Applications with Scala E-Book

Diego Pacheco

0,0
41,99 €

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

Mehr erfahren.
Beschreibung

Write modern, scalable, and reactive applications with the power of Scala

About This Book

  • Delves into the intricacies of functional reactive programming with Scala
  • Explores frameworks like Akka, Play and Slick used to develop efficient applications
  • A step by step guide with plenty of examples showing practical implementation of essential concepts

Who This Book Is For

If you are a Java or JVM developer who wants to use Scala to build reactive functional applications for the JVM platform, then this book is for you. Prior knowledge of Java or functional programing would help. No Scala knowledge is required.

What You Will Learn

  • Use Akka to create a chat service for your app
  • Equip yourself with the techniques and tools to build reports and build database persistence with Scala and Slick
  • Develop a customer-facing Rest API that makes use of Scala and Spray
  • Make use of the Scala web development principles and scale up the architecture of your application
  • Get familiar with the core principles and concepts of Functional Programming
  • Use the Play framework to create models, controllers, and views
  • Develop reactive backing frameworks by writing code with RxScala
  • Discover what proper testing entails with Scala using behavior-driven development

In Detail

Scala is known for incorporating both object-oriented and functional programming into a concise and extremely powerful package. However, creating an app in Scala can get a little tricky because of the complexity the language has. This book will help you dive straight into app development by creating a real, reactive, and functional application. We will provide you with practical examples and instructions using a hands-on approach that will give you a firm grounding in reactive functional principles.

The book will take you through all the fundamentals of app development within Scala as you build an application piece by piece. We've made sure to incorporate everything you need from setting up to building reports and scaling architecture. This book also covers the most useful tools available in the Scala ecosystem, such as Slick, Play, and Akka, and a whole lot more. It will help you unlock the secrets of building your own up-to-date Scala application while maximizing performance and scalability.

Style and approach

This book takes a step-by-step approach to app development with Scala. It will place special emphasis on functional language. It will teach you the core benefits of Scala and the fundamentals of functional programming by developing a robust application.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 342

Veröffentlichungsjahr: 2016

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.



Table of Contents

Building Applications with Scala
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Introduction to FP, Reactive, and Scala
Functional programming
Principles of functional programming
Immutability
Disciplined state
Pure functions and no side effects
First-class functions and higher-order functions
Type systems
Referential transparency
Installing Java 8 and Scala 2.11
Read Eval Print and Loop - REPL
Scala Hello World using the REPL
Scala REPL Hello World program
Scala object-oriented HelloWorld program
Scala HelloWorld App in the Scala REPL
Java HelloWorld application
Scala language - the basics
Scala variables - var and val
Scala REPL var usage
Scala val usage at the Scala REPL
Creating immutable variables
Scala variable type in the Scala REPL
Scala variables with explicit typing at the Scala REPL
Scala conditional and loops statements
If statements in Scala REPL
If statements in return statements in Scala REPL
Basic for loop in Scala REPL
For with List in Scala REPL
For with if statements for filtering - Scala REPL
Java code for filtering even numbers
For comprehensions
For comprehension in Scala REPL
Java code for performing filtering with collections
Scala collections
Creating, removing, and getting an item from a mutable list in Scala REPL
Scala tuples
Scala immutable Map in Scala REPL
Scala mutable Maps at Scala REPL
Monads
Scala Map function in Scala REPL
Option Monad in Scala
A list of all methods using the Scala REPL
Scala class, traits, and OO programming
A simple Scala class in Scala REPL
Scala plain old Java object in Scala REPL
Person class in Java
Traits and inheritance
Scala inheritance code in Scala REPL
Scala traits sample code in Scala REPL
Scala traits using variable mixing technique at Scala REPL
Scala type alias sample in Scala REPL
Case classes
Scala case classes feature in Scala REPL
Pattern Matcher
Simple Pattern Matcher in Scala
Advanced pattern matcher in Scala REPL
Advanced complex pattern matcher in Scala REPL
Partial functions
Simple Partial function in Scala REPL
Scala PartialFunction without OO using case statements in Scala REPL
PartialFunction composition in Scala REPL
Package objects
package.scala
MainApp.scala
Functions
Partial application
Partial function in Scala REPL
Curried functions
Curried functions - Scala REPL
Curried transformation in Scala REPL
Operator overloading
Scala operator overloading in Scala REPL
Implicits
Scala Implicits in SCALA REPL
Implicit Parameter at Scala REPL
Futures
Simple Future code in Scala REPL
A complete Future sample at Scala REPL
Reactive Programing and RxScala
Simple Observables Scala with RxScala
Simple Observables Scala with RxScala - Execution in the console
Complex Scala with RxScala Observables
Summary
2. Creating Your App Architecture and Bootstrapping with SBT
Introducing SBT
Installing SBT on Ubuntu Linux
Getting started with SBT
Adding dependencies
Generating Eclipse project files from SBT
Application distribution
Hello world SBT / Scala App
Bootstrapping our Play framework app with Activator
Activator shell
Activator - compiling, testing, and running
Summary
3. Developing the UI with Play Framework
Getting started
Creating our models
Creating routes
Creating our controllers
Working with services
Configuring the Guice module
Working with views(UI)
Summary
4. Developing Reactive Backing Services
Getting started with reactive programming
IPriceService - Scala trait
PriceService - RxScala PriceService implementation
Guice Injection - Module.scala
NGServiceEndpoint
Play framework and high CPU usage
RndDoubleGeneratorController
IRndService.scala - Scala trait
RndService.scala - RndService implementation
Module.scala - Guice Injections
main.scala.html
product_details.scala.html
Summary
5. Testing Your Application
Unit testing principles
Making code testable
Isolation and self-contained tests
Effective naming
Levels of testing
Testing with Junit
Behavior-Driven Development - BDD
MyFirstPlaySpec.scala - First BDD with ScalaTest and the Play framework
Testing with Play framework support
ProductService.scala - FIX the code issue
ImageServiceTestSpec.scala - ImageService Test
ReviewServiceTestSpec.scala - ReviewService test
Testing routes
RoutesTestingSpec.scala - Play framework route testing
Controller testing
RndDoubleGeneratorControllerTestSpec.scala - RndDoubleGeneratorController tests
IntegrationSpec.scala
ProductControllerTestSpec.scala
product_index.scala.html
ImageControllerTestSpec.scala
image_index.scala.html
ReviewControllerTestSpec.scala
review_index.scala.html
ApplicationSpec.scala
NGServiceImplTestSpec.scala
NGServiceEndpointControllerTest.scala
Summary
6. Persistence with Slick
Introducing the Slick framework
MySQL setup
Configuring Slick in our Play framework app
Configure the database connection
FPM Mapping
ProductDao
ReviewDAO
ImageDao
Slick evolutions
Refactoring services
Refactoring controllers
Configuring DAO packages in Guice
Refactoring tests
Generic mocks
Service tests
Controller tests
Running the application
Summary
7. Creating Reports
Introducing JasperReports
JasperReports workflow
Jasper sessions
Installing Jaspersoft Studio 6
Configuring MySQL Data Adapter in Jaspersoft Studio
Creating a product report
Creating a review report
Creating an image report
Integrating JasperReports with Play framework
build.sbt
Generic report builder
Adding the report to the product controller
Adding the report to the review controller
Adding the report to the image controller
Routes - adding new report routes
New centralized reports UI
Adding the report button for each view
Summary
8. Developing a Chat with Akka
Adding the new UI introduction to Akka
Introduction to the Actor model
What is an Actor?
Message exchange and mailboxes
Coding actors with Akka
Actor routing
Persistence
Creating our chat application
The chat protocol
The chat controller
Implementing the chat controller
Configuring the routes
Working on the UI
Adding Akka tests
Scala test for Akka Actor
Chat room Actor test
Chat Bot Admin Actor test
Summary
9. Design Your REST API
Introduction to REST
REST API design
HTTP verbs design
Uniform API
Response with HTTP status codes
REST API patterns
API versioning
Some anti-patterns to be avoided
Creating our API with REST and JSON
RestApiContoller
REST API Front Controller implementation
JSON mapping
Configuring new routes
Testing the API using the browser
Creating a Scala client
Configuring plugins.sbt
Configuring build.sbt
Scala client code
Creating our REST client proxies
Creating ScalaTest tests for the proxies
Adding back pressure
The leaky bucket algorithm
Scala leaky bucket implementation
Testing back pressure
Adding Swagger support
Swagger UI
Build and install Swagger Standalone
Summary
10. Scaling up
Standalone deploy
Reports folder
Changing report builder
Defining the secret
Running the standalone deploy
Architecture principles
Service orientation (SOA/microservices)
Performance
Scalability/Resiliency
Scalability principles
Vertical and horizontal scaling (up and out)
Caching
Load balancer
Throttling
Database cluster
Cloud computing/containers
Auto Scaling
A note about automation
Don't forget about telemetry
Reactive Drivers and discoverability
Mid-Tier load balancer, timeouts, Back pressure, and caching
Scaling up microservices with an Akka cluster
Scaling up the infrastructure with Docker and AWS cloud
Summary

Building Applications with Scala

Building Applications with Scala

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: December 2016

Production reference: 1021216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-148-3

www.packtpub.com

Credits

Author

Diego Pacheco

Copy Editor

Sonia Mathur

Reviewer

Yuanhang Wang

Project Coordinator

Suzanne Coutinho

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Tejal Daruwale Soni

Content Development Editor

Rohit Singh

Graphics

Jason Monteiro

Technical Editor

Jijo Maliyekal

Production Coordinator

Melwyn Dsa

About the Author

Diego Pacheco is an experienced software architect and DevOps practitioner with over 10 years of solid experience. He has led architecture teams using open source solutions such as Java, Scala, Amazon Web Services (AWS), Akka, Apache Cassandra, Redis, ActiveMQ, NetflixOSS Stack - Simian Army, RxJava, Karyon, Eureka, and Ribbon on cig customers in Brazil, London, Barcelona, India, and the USA. Diego has a passion for functional programming and is currently working as a software architect/agile coach with Scala, Akka, and NetflixOSS. During his free time, he enjoys gaming, blogging, and playing wicked tunes on his guitar. You can check out his blog at http://diego-pacheco.blogspot.in/.

Some of his core skills include the following:

 Architecture design and architecture coding for high scalable systems Distributed systems using SOA and microservices principles, tools, and techniques Performance tuning and DevOps engineering Functional programming and Scala Agile coaching and servant leadership for architecture teams Consultancy on development practices with XP/Kanban

More about him can be found at the following:

Linkedin: https://www.linkedin.com/in/diegopachecorsBlog: http://diego-pacheco.blogspot.in/Github: https://github.com/diegopachecoSlideshare: http://www.slideshare.net/diego.pacheco/presentationsPresentations: https://gist.github.com/diegopacheco/ad3e3804a5071ef219d1

His recent lectures include Netflix (https://www.youtube.com/watch?v=Z4_rzsZd70o&feature=youtu.be), QCon (http://qconsp.com/sp2016/speaker/diego-pacheco), and Amazon (http://www.meetup.com/Sao-Paulo-Amazon-Web-Services-AWS-Meetup/events/229283010/).

Acknowledgments

First of all, I'm very thankful for everything God has given to me in life. So, I need to say thank you to God at least three times. Thank you God, thank you God, thank you God. I’m very glad to have finished this book, and I also need to say a big thank you to all my family and supportive friends, especially Andressa Bicca, my true love; my mother, Denise Maris; my grandmother, Walkyria; and my dear friends, Margarida Avila, Adão Avila, Israel Prestes, and Tais da Rosa, for all their love and support. I need to say thanks to Packt, especially to Kirk D'costa and Rohit Kumar Singh for being great editors. Also, I need to say thank you to ilegra.com and especially to Ivã Boesing and Romulo Dornelles for all the space, trust, and support. Also, I cannot forget to say thank you to my coworkers, customers, and friends, who are great people to work with, and who I’ve learned a lot from: Sam Sgro, Daniel Wildt, Anibal Rojas, Alexandre Poletto, Jeferson Machado, Nilseu Padilha, Jackson Santos, Christophe Marchal, Joel Correa, and Rafael Souza. Finally, thank you to all of you who bought this book and have read it--you are awesome!

About the Reviewer

Yuanhang Wang describes himself as an enthusiast of purely functional programming and neural networks, with a primary focus on Domain Specific Language (DSL) design, and he has dabbled in several functional programming languages. He is currently a data scientist at China Mobile Research Center, working on a typed data processing engine and optimizer built on top of several big data platforms.

www.PacktPub.com

For support files and downloads related to your book, please visit www.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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

Functional programming started in academia and ended up in the IT industry. The Scala language is a multi-paradigm language used by big players and large organizations that helps you get the correct (in the sense of pure functional programming) software and, at the same time, software that is practical and scalable.

Scala has a very rich ecosystem, including Play Framework, Akka, Slick, Gatling, Finable, and more. In this book, we will start right from the basic principles and ideas on functional and ReactiveX programming, and through practical examples, you will learn how to code with the most important frameworks of the Scala ecosystem, such as Play, Akka, and Slick.  

You will learn how to bootstrap a Scala application with SBT and Activator, how to build a Play and Akka application step by step, and we cover the theory of how to scale massive Scala applications with cloud and the NetflixOSS stack.  This book will help you to go from the basic subjects to the most advanced ones in order to make you a Scala expert.

What this book covers

Chapter 1, Introduction to FP, Reactive, and Scala, looks at how to set up a Scala development environment, the difference between functional programming and object-oriented programming, and the concepts of functional programming.

Chapter 2, Creating Your App Architecture and Bootstrapping with SBT, discusses the overall architecture, SBT basics, and how to create your own application.

Chapter 3, Developing the UI with Play Framework, covers the principles of web development in Scala, creating our models, creating our views, and adding validations.

Chapter 4, Developing Reactive Backing Services, introduces you to reactive programming principles, refactoring our controllers, and adding Rx Scala to our services.

Chapter 5, Testing Your Application, looks into testing principles with Scala and JUnit, behavior-driven development principles, using ScalaTest specs and DSL in our tests, and running our tests with SBT.

Chapter 6, Persistence with Slick, covers principles of database persistence with Slick, working with Functional Relational Mapping in your application, creating the queries you need with SQL support, and improving the code with async database operations.

Chapter 7, Creating Reports, helps you understand Jasper reports and add database reports to your application.

Chapter 8, Developing a Chat with Akka, discusses the actor model, actor systems, actor routing, and dispatchers.

Chapter 9, Design Your REST API, looks into REST and API design, creating our API with REST and JSON, adding validations, adding backpressure, and creating a Scala client.

Chapter 10, Scaling Up, touches upon the architecture principles and scaling up the UI, reactive drivers, and discoverability. It also covers middle-tier load balancers, timeouts, back pressure, and caching, and guides you through scaling up microservices with an Akka cluster and scaling up the infrastructure with Docker and AWS cloud.

What you need for this book

For this book, you will need the following:

Ubuntu Linux 14 or superiorJava 8 update 48 or superiorScala 2.11.7Typesafe Activator 1.3.9Jasper Reports DesignerWindows fonts for LinuxEclipse IDE

Who this book is for

This book is for professionals who want learn Scala, as well as functional and reactive techniques. This book is mainly focused on software developers, engineers, and architects. This is a practical book with practical code; however, we also have theory about functional and reactive programming.  

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The next step is to create the environment variable called SCALA_HOME, and to put the Scala binaries in the PATH variable."

A block of code is set as follows:

package scalabook.javacode.chap1; public class HelloWorld { public static void main(String args[]){ System.out.println("Hellow World"); } }

Any command-line input or output is written as follows:

export JAVA_HOME=~/jdk1.8.0_77export PATH=$PATH:$JAVA_HOME/bin

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The Actor behavior is the code you will have inside your Actor."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

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

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

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

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Building-Applications-with-Scala. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/BuildingApplicationswithScala_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Introduction to FP, Reactive, and Scala

In our first chapter, we will learn the basic concepts of Functional Programing (FP), reactive programming, and the Scala language. These concepts are listed as follows:

Setting up a Scala development environment with Eclipse Scala IDE.Basic constructs of the language like var, val, for, if, switch, and operator overload.The difference between FP and object-oriented programming.Principles of pure FP: immutability, no side effects, state discipline, composition, and higher order functions.Concepts of FP such as lambda, recursion, for comprehensions, partial functions, Monads, currying, and functions.Pattern Matcher, recursion, reflection, package objects, and concurrency.

Let's get going!

Functional programming

FP is not new at all. The very first implementation of FP is Lisp and is dated from the 1950s. Currently, we are living in a post-functional programming era, where we have the strong math principles and ideas from the 50s mixed with the most modern and beautiful piece of engineering, also know as the Java Virtual Machine (JVM). Scala is a post-functional programming language built on top of the JVM. Being on top of the JVM gives us a lot of benefits such as the following:

Scala is a post-functional programming language built on top of the JVM. Being on top of the JVM gives us a lot of benefits such as the following:

Reliability and performance: Java is used by 10 out of 10 top websites we have currently, like Netflix, Apple, Uber, Twitter, Yahoo, eBay, Yelp, LinkedIn, Google, Amazon, and many others. JVM is the best solution at scale and is battle-tested by these web-scale companies.Native JVM eco-system: Full access to all of the Java ecosystem including frameworks, libraries, servers, and tools.Operations leverage: Your operation team can run Scala in the same way they run Java.Legacy code leverage: Scala allows you to easily integrate Scala code with Java code. This feature is great because it enables Java legacy system integration inside the box.Java interoperability: A code written in Scala can be accessed in Java.

Scala was created in 2001 at EPFL by Martin Odersky. Scala is a strong static-typed language, and was inspired by another functional language called Haskell. Scala addresses several criticisms of the Java language, and delivers a better developer experience through less code and more concise programs, without losing performance.

Scala and Java share the same infrastructure as the JVM, but in terms of design, Scala is a different language in comparison with Java. Java is an imperative object-oriented language and Scala is a post-functional, multiparadigm programing language. FP works with different principles than object-oriented programing (OOP). OOP got very popular and well established in enterprise thanks to languages like Java, C#, Ruby, and Python. However, languages like Scala, Clojure, F#, and Swift are gaining a huge momentum, and FP has grown a lot in the last 10 years. Most of the new languages are pure functional, post-functional, or hybrid (like Java 8). In this book, you will see Scala code compared with Java code so you can see by yourself how Scala is way more compact, objective, and direct than Java and imperative OOP languages.

FP started at academia and spread to the world; FP is everywhere. Big Data and Stream processing solutions like Hadoop and Spark (built on top of Scala and Akka) are built on top of FP ideas and principles. FP spread to UI with RxJavaScript - you can even find FP in a database with Datomic (Clojure). Languages like Clojure and Scala made FP more practical and attractive to enterprise and professional developers. In this book, we will be exploring both principles and practical aspects of the Scala language.

Principles of functional programming

FP is a way of thinking, a specific style of constructing and building programs. Having an FP language helps a lot in terms of syntax, but at the end of the day, it's all about ideas and developer mindset. FP favors disciplined state management and immutability in a declarative programming way rather than the imperative programming mostly used by OOP languages such as Java, Python, and Ruby.

FP has roots in math back to Lambda calculus - a formal system developed in the 1930s. Lambda calculus is a mathematical abstraction and not a programming language, but it is easy to see its concepts in programming languages nowadays.

Imperative programming uses statements to change the program state. In other words, this means you give commands to the program to perform actions. This way of thinking describes a sequence of steps on how the program needs to operate. What you need to keep in mind is the kind of style focus on how FP works in a different way, focusing on what the program should accomplish without telling the program how to do it. When you are coding in FP, you tend to use fewer variables, for loops, and IFS, and write more functions and make function composition.

The following are the CORE principles of FP:

ImmutabilityDisciplined statePure functions and no side effects/disciplined statesFirst class functions and high order functionsType systemsReferential transparency

Let's understand these principles in detail.

Immutability

The concept of immutability is the CORE of FP, and it means that once you assign a value to something, that value won't change. This is very important, because it eliminates side effects (anything outside of the local function scope), for instance, changing other variables outside the function. Immutability makes it easier to read code, because you know the function that you are using is a pure function. Since your function has a disciplined state and does not change other variables outside of the function, you don't need to look at the code outside the function definition. This sounds like you're not working with state at all, so how would it be possible to write professional applications this way? Well, you will change state but in a very disciplined way. You will create another instance or another pointer to that instance, but you won't change that variable's value. Having immutability is the key to having better, faster, and more correct programs, because you don't need to use locks and your code is parallel by nature.

Disciplined state

Shared mutable state is evil, because it is much harder to scale and to run it concurrently. What is shared mutable state? A simple way to see it is as a global variable that all your functions have access to. Why is this bad? First of all, because it is hard to keep this state correct since there are many functions that have direct access to this state. Second, if you are performing refactoring, this kind of code is often the hardest to refactor as well. It's also hard to read this code. This is because you can never trust the local method, since your local method is just one part of the program. And with mutable state, you need to look up for all the functions that use that variable, in order to understand the logic. It's hard to debug for the very same reason. When you are coding with FP principles in mind, you avoid, as much as possible, having a shared mutable state. Of course you can have state, but you should keep it local, which means inside your function. This is the state discipline: you use state, but in a very disciplined way. This is simple, but it could be hard especially if you are a professional developer, because this aspect is now usual to see in enterprise languages such as Java, .NET, Ruby, and Python.

Pure functions and no side effects

Pure functions are the ones with no side effects. Side effects are bad, because they are unpredictable and make your software hard to test. Let's say you have a method that receives no parameters and returns nothing--this is one of the worst things we could have, because how do you test it? How can you reuse this code? This is not what we call a pure function. What are the possible side effects? Database call, global variables, IO call, and so on. This makes sense, but you cannot have a program with just pure functions, because it won't be practical.

First-class functions and higher-order functions

First-class means that the language treats functions as first-class citizens. In other words, it means having language support to pass functions as arguments to other functions and to return values as functions. First-class function also implies that the language allows you to store functions as variables or any other data structure.

Higher-order functions are related to First-class functions, but they are not the same thing. Higher-order functions often means language support for partial functional application and Currying. Higher-order functions are a mathematical concept where functions operate with other functions.

Partial functions are when you can fix a value (argument) to a particular function, which you may or may not change later on. This is great for function composition.

Currying is a technique to transform a function with multiple parameters in a sequence of functions with each function having a single argument. Scala language does not force currying, however, languages like ML and Haskell almost always use this kind of technique.

Type systems

Type system is all about the compiler. The idea is simple: you create a type system, and by doing so, you leverage the compiler to avoid all kinds of mistakes and errors. This is because the compiler helps in making sure that you only have the right types as arguments, turn statements, function composition, and so on. The compiler will not allow you do make any basic mistakes. Scala and Haskell are examples of languages that are Strong-type. Meanwhile, Common Lisp, Scheme, and Clojure are dynamic languages that may accept wrong values during compilation time. One of the biggest benefits of the strong type system is that you have to write fewer tests, because the compiler will take care of several issues for you. For instance, if you have a function that receives a string, it could be dangerous, because you can pass pretty much anything in a string. However, if you have a function that receives a type called salesman, then you don't write a validation to check if it is a salesman. All this may sound silly, but in a real application, this saves lots of lines of code and makes you program better. Another great benefit of strong typing is that you have better documentation, as your code becomes your documentation, and it's way more clear what you can or can't do.

Referential transparency

Referential transparency is a concept which works close with pure functions and immutability since your program has fewer assignment statements, and often when you have it, you tend to never change that value. This is great because you eliminate side effects with this technique. During program execution, any variable can be replaced since there are no side effects, and the program becomes referentially transparent. Scala language makes this concept very clear the moment you declare a variable.

Installing Java 8 and Scala 2.11

Scala requires JVM to work, so we need get the JDK 8 before installing Scala. Go to the Oracle website, and download and install JDK 8 from http://www.oracle.com/technetwork/pt/java/javase/downloads/index.html.

Once you've downloaded Java, we need to add Java to the PATH variable; otherwise, you can use the terminal. We do this as follows:

$ cd ~/$ wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u77-b03/jdk-8u77-linux-i586.tar.gz"$ tar -xzvf $ jdk-8u77-linux-x64.tar.gz $ rm -f jdk-8u77-linux-x64.tar.gz

The next step is to create the environment variable called JAVA_HOME, and to put the Java 8 binaries in the PATH variable. In Linux, we need to edit the ~/.bashrc file, and export the variables we need, like in the following:

export JAVA_HOME=~/jdk1.8.0_77export PATH=$PATH:$JAVA_HOME/bin

Save the file, and then on the same terminal we need to source the file via $ source ~/.bashrc

Now we can test our Java 8 installation. Just type in $ java -version. You should see something like the following:

$ java -versionjava version "1.8.0_77"Java(TM) SE Runtime Environment (build 1.8.0_77-b03)Java HotSpot(TM) Server VM (build 25.77-b03, mixed mode)

Let's get started. We will be using the latest Scala version 2.11.8. However, the code inside this book should work with any Scala 2.11.x version. First of all, let's download Scala from http://www.scala-lang.org/.

Scala works on Windows, Mac, and Linux. For this book, I will show how to use Scala on Ubuntu Linux(Debian-based). Open your browser and go to http://www.scala-lang.org/download/.

Download scala 2.11.8: it will be a TGZ file. Extract it and add it to your path; otherwise, you can use the terminal. Do this as follows:

$ cd ~/$ wget http://downloads.lightbend.com/scala/2.11.8/scala-2.11.8.tgz$ tar -xzvf scala-2.11.8.tgz$ rm -rf scala-2.11.8.tgz

The next step is to create the environment variable called SCALA_HOME, and to put the Scala binaries in the PATH variable. In Linux, we need to edit the ~/.bashrc file and export the variables we need, like in the following:

export SCALA_HOME=~/scala-2.11.8/export PATH=$PATH:$SCALA_HOME/bin

Save the file, and then, on the same terminal, we need to source the file via $ source ~/.bashrc.

Now we can test our Scala installation. Just type in $ scala -version. You should see something like the following:

$ scala -versionScala code runner version 2.11.8 -- Copyright 2002-2016, LAMP/EPFL

You have successfully installed Java 8 and Scala 2.11. Now we are ready to start learning the FP principles in Scala. For this, we will be using the Scala REPL in the beginning. Scala REPL is bundled with the default Scala installation, and you just need to type $ scala in your terminal as follows:

$ scalaWelcome to Scala 2.11.8 (Java HotSpot(TM) Server VM, Java 1.8.0_77).Type in expressions for evaluation. Or try :help.scala>Scala REPL

Congratulations! You have installed Java 8 and Scala 2.11 successfully.

Read Eval Print and Loop - REPL

Read Eval Print and Loop (REPL) is also know as a language shell. Many other languages have shells, like Lisp, Python, and Ruby for instance. The REPL is a simple environment to experiment the language in. It's possible to write very complex programs using REPL, but this is not the REPL goal. Using REPL does not invalidate the usage of an IDE like Eclipse or IntelliJ IDEA. REPL is ideal for testing simple commands and programs without having to spend much time configuring projects like you do with an IDE. The Scala REPL allows you to create a variable, functions, classes, and complex functions as well. There is a history of every command you perform; there is some level of autocomplete too. As a REPL user, you can print variable values and call functions.

Scala language - the basics

Scala is a statically typed language with a very expressive type system which enforces abstractions in a safe yet coherent manner. All values in Scala are Java objects (primitives which are unboxed at runtime), because at the end of the day, Scala runs on the Java JVM. Scala enforces immutability as a core FP principle. This enforcement happens in multiple aspects of the Scala language, for instance, when you create a variable, you do it in an immutable way, when you use an collection, you will use a immutable collection. Scala also lets you use mutable variables and mutable structures, but by design, it favors immutable ones.

Scala variables - var and val

When you are coding in Scala, you create variables using the operator var, or you can use the operator val. The operator var allows you to create a mutable state, which is fine as long as you make it local, follow the CORE-FP principles and avoid a mutable shared state.

Scala REPL var usage

We will see how to use var in Scala REPL as follows: