41,99 €
Write modern, scalable, and reactive applications with the power of Scala
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.
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.
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:
Seitenzahl: 342
Veröffentlichungsjahr: 2016
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
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
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:
More about him can be found at the following:
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/).
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!
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.
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.
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.
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.
For this book, you will need the following:
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.
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/binNew 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."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
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!
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.
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 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.
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.
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:
Let's get going!
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:
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.
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:
Let's understand these principles in detail.
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.
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 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 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 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 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.
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.gzThe 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/binSave 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.tgzThe 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/binSave 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/EPFLYou 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 REPLCongratulations! You have installed Java 8 and Scala 2.11 successfully.
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 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.
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.
We will see how to use var in Scala REPL as follows:
