search
left
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
right
Learning Scala Programming
Learning Scala Programming

Learning Scala Programming: Object-oriented programming meets functional reactive to create Scalable and Concurrent programs

By Vikash Sharma
€28.99 €19.99
Book Jan 2018 426 pages 1st Edition
eBook
€28.99 €19.99
Print
€37.99
Subscription
€14.99 Monthly
eBook
€28.99 €19.99
Print
€37.99
Subscription
€14.99 Monthly

What do you get with eBook?

Feature icon Instant access to your Digital eBook purchase
Feature icon Download this book in EPUB and PDF formats
Feature icon Access this title in our online reader with advanced features
Feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 30, 2018
Length 426 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788392822
Category :
Languages :
toc View table of contents toc Preview Book

Learning Scala Programming

Chapter 1. Getting Started with Scala Programming

"When you don't create things, you become defined by your own tastes rather than ability, your tastes only narrow and exclude people. So create."

- Why the Lucky Stiff

Scala is easy to get into but too deep to get a grip on. As the name suggests, Scala means A Scalable Language, a programming language that grows with your programming abilities. This chapter introduces you to this very popular language. 

In this chapter, we will cover the following topics:

  • Introduction to Scala
  • Scala advantages
  • Working with Scala
  • Running our first program

Introduction to Scala


Consider a scenario where you get a paragraph and a word and you are asked to get the number of occurrences for that word. You're lucky enough to know a language such as Java. Your solution might look like this:

String str = "Scala is a multi-paradigm language. Scala is scalable too."
int count = 0;
for (stringy: str.split (" ")) {
    if (word.equals (stringy))
        count++;
}
System.out.println ("Word" + word + " occurred " + count + " times.")

That was easy, wasn't it? Now our Scalable language has a simple way of accomplishing this. Let's take a look at that:

val str = "Scala is a multi-paradigm language. Scala is scalable too."
println ("Word" + word + " occurred " + str.split(" ").filter(_ == word).size + " times.")

That's it, a one-liner solution for the same problem. The code may not look familiar right now, but gradually you'll have command over it. By the end of this chapter, we'll understand everything that's needed to run a Scala program, not just a Hello World program, but one that does something.

Scala's no different. It runs on JavaVirtualMachine (JVM), so Java folks must have an idea about it. If not, JVM is defined as an abstract computing machine that operates on a set of instructions (Java Bytecode). It enables a machine to run a Java program. So here's the conclusion: when we write Scala programs and compile them, they are converted into Java Bytecode and then run on JVM. Scala interoperates with all Java libraries. It's easier and, of course, possible to write our own Scala code and also incorporate library functions written in Java.

Scala is a multi-paradigm language; it's a mixture of object-oriented and functional programming. But what good is it to us?

A programming paradigm

A paradigm is simply a way of doing something. So a programming paradigm means a way of programming or a certain pattern of writing programs. There are a number of programming paradigms in existence, but four of them have gained popularity:

  • Imperative Paradigm: First do this and then do that
  • Functional Paradigm: Evaluate and use
  • Logical Paradigm: Answer through solution
  • Object-Oriented Paradigm: Send messages between objects to simulate temporal evolution of a set of real-world phenomena

Object-oriented versus functional paradigms 

With its roots in the mathematics discipline, the functional programming paradigm is simple. It works on the theory of functions which produce values that are immutable. Immutable values mean they can't be modified later on directly. In the functional paradigm, all computations are performed by calling self/other functions. Functions are first-class citizens in the functional world. This opens up a new world of possibilities where all computations are driven by a certain need.

The object-oriented planet revolves around encapsulation and abstractions. The logical grouping of components makes maintenance of larger and complex programs easier. Data and models are encapsulated in objects. Information hiding is effective for containing an object's properties. Inheritance hierarchies, the concept of classes, and messaging between objects makes the whole model/pattern of object-oriented programming a partial success.

Scala is multi-paradigm

Scala, being a multi-paradigm language, supports both paradigms. As we're learning Scala, we have the power of both of these paradigms. We can create functions as we need them, and also have objects talking to other objects. We can have class hierarchies and abstractions. With this, dominance over a particular paradigm will not affect another.

Today the need for concurrency, immutability, heterogeneity, reactiveness, and fault tolerant architectures with ever-shrinking development life cycles has drastically increased. In this era, languages such as Scala do more than they need to with their support for functional as well as object-oriented programming.

For a programmer like us, a language is a tool to create something meaningful. We tend to reuse and manipulate other tools as well, in our case let's say other libraries. Now, we would like to work with a language which provides us extensibility and flexibility in terms of its use. Scala does this. This powerful language lets you mix in newly created traits (you may not have heard about this, but you can compare it to Java's interfaces). There are a number of ways we can make our code more meaningful and of course concise. If used smartly, you can create your own custom constructs with native language features. So this language is as exciting as you are!

This is one of the reasons to learn it. There are other reasons behind why we would choose Scala over any other languages, and there's quite a few. Let's take them one by one. But first let's get confused:

"Scala is a functional language, supports multiple paradigms, and every function in Scala is an object."

Great! Now you know three main characteristics of this language. But it's hard to swallow. It's a functional language, and every function is an object. Really?

The following is an example of a trait defined in Scala, called Function1:

package scala
trait Function1[A, B] {
        def apply(x: A) : B
}

There are more of these, from Function0 to Function22. There's a certain way of using these. We'll be using them many times in this book. We also refer to these as A => B (we call it, A to B). It means this function takes a parameter of type A, does some operation as defined, and returns a value of type B:

val answer = new Functiona1[Int, Int] {
        def apply(x: Int): Int = x * 2
}

This feels a bit too much to start with but getting familiar with these constructs is a good idea. val is a keyword used to declare a value type. It means, once declared and instantiated, you can't change it further. This answer = (x: Int) => x * 2 becomes a function literal that can be passed to another function. We get to this point because we were able to instantiate an object of our Function1 trait (we'll see how this works in Chapter 7, Next Steps in Object-Oriented Scala).

Think of any two lucky numbers, now represent how you can add them. Suppose your numbers were 42 + 61. Here, your numbers 42 and 61 are objects of type Int and + is a method on type Int. This is the way you and Scala are going to treat entities. We'll treat entities as objects and operations performed on them as methods. And this is what makes this language scalable.

We can perform functional operations where inputs are transformed to outputs rather than changing data/state of them. With this in mind, most of our operations (almost all) will not depend on state change; means functions are not going to have side effects. One example could be a function which takes your date of birth and returns your age in terms of the number of years and months:

class YearsAndMonths(years: Int, months: Int)
def age(birthdate: Date): YearsAndMonths = //Some Logic

This is a pure function because it does not manipulate the input. It takes input, transforms, and gives output. Case class is just to help us here define the age in a certain manner. With this, we can introduce more terminology called referentially transparent methods. Our age method can be called referentially transparent. These method calls can be replaced by the result without changing any meaning/semantics of your program.

Pure functions, the concept of immutability, and referential transparency are here only to make this language more powerful. There are more reasons to choose this language as a tool for your next application.

Scala advantages


We're smart programmers. We've already set expectations on the choice of our language. Our language should be extensive and flexible enough. It should be friendly, support libraries written in languages such as Java, be easy to work with, have good online support, and a whole lot more. And guess what! Scala gives you the complete package.

Runs on JVM

Consider efficiency and optimization as factors for a language to be well performant. Scala utilizes JVM for this. JVM uses Just in Time (JIT) compilation, adaptive optimization techniques for improved performance. Running on JVM makes Scala interoperable with Java. You've multitudinous libraries available as tools for reuse.

If anywhere in your mind you're comparing Java and Scala's performance, let's get it clear. Both Java and Scala programs are compiled into bytecode. JVM understands bytecode and runs it for you. So it mostly depends on the way you write a program. Scala blends in some syntax sugar, compiler logic that can cause your program to be more/less performant than Java. Mix-ins using traits can be an asset to your program architecture but may affect your program's performance. But alternatives in Java may cost the same or more. So it is more about your core understanding of constructs and how your code is going to compile and perform. It takes some time and effort to understand so the choice is yours; as a smart programmer, you may go for a syntactically powerful language.

Super smart syntax

You are going to write succinct code with Scala. There are a lot of examples we can look at to see Scala's syntax conciseness. Let's take an example from Scala's rich collections and create a Map:

val words = Map ("Wisdom" -> "state of being wise")
println(words("Wisdom"))

> state of being wise

The preceding code is creating a map of words and their meaning. Only Map ("Wisdom" -> "state of being wise") is the amount of code we have to write to make it possible. No need to add semicolons. We did not even mention the type of our value and the Scala compiler was able to infer it. Type inference is a characteristic of this language. Because of Type inference, a lot of times we omit type declaration and use a value directly. This way, using only a minimal set of words/tokens you can express the logic to implement them. Constructs like case classes and pattern matching take away the extra effort one might have to make and makes writing code joyful. It also helps you reduce written code by a good margin.

Best of both worlds

Scala is a mixture of functional and object-oriented worlds. It gives two benefits. First, you can leverage the power of functional constructs: higher-order functions, nested functions, pure functions, and closures. You get to work with more available (and recommended) immutable data structures. Working with immutable code helps in eliminating code that can introduce side effects or state change. This also makes this language suitable for concurrent programming. This is just another advantage Scala provides. Second, you've all the object-oriented goodies available.

You can define traits, mix them in with classes or objects, and achieve inheritance. The creation of objects, defining abstracts, and sub-classing is also possible in Scala.

Type is the core

In the early days (great, if even in the present) you may have come across this:

f : R -> N

This is the mathematical representation of a function. This is how we denote any function f's domain and co-domains. In this case a function, f maps values from a set of real numbers to a set of natural numbers. With this deep abstraction level, you can think of Scala's rich type system. Some of the numerous types available are parameterized, structural, compound, existential, path-dependent, higher-kinded, and yes, we are discussing abstract types. An explanation of all these is beyond the scope of this book. But if you're curious, you may refer to Scala documentation at https://www.scala-lang.org/documentation/. Knowledge of these helps a lot when designing frameworks or libraries.

Concurrency made easy

Scala recommends the use of immutable data structures, immutable collections, use of value types, functional compositions, and transformations. Along with these, the use of actors and other concurrent constructs have made it so easy to write concurrent programs. Mostly, programmers do not have to deal with the complication of thread life cycle management, because of modern constructs such as actors and reactors available in the form of native support and through libraries. Akka is one of these toolkits available, written in Scala. Also, the use of futures and promises enables writing asynchronous code.

Asynchronous code

Simply defined, asynchronous code is where your program control returns immediately after calling a block of instruction (that is a function), having started some parallel/ background effort to complete your request. This means your program flow will not stop because of a certain function taking time to complete.

Asynchronous versus parallel versus concurrent programming

Asynchronous programming involves some calculations time-intensive tasks, which on the one hand are engaging a thread in the background but do not affect the normal flow of the program.

Parallel programming incorporates several threads to perform a task faster and so does concurrent programming. But there's a subtle difference between these two. The program flow in parallel programming is deterministic whereas in concurrent programming it's not. For example, a scenario where you send multiple requests to perform and return responses regardless of response order is said to be concurrent programming. But where you break down your task into multiple sub-tasks to achieve parallelism can be defined as the core idea of parallel programming.

Now available for the frontend

Scala.js is specifically designed for the frontend and helps you avoid type-based mistakes as Scala.js is able to infer to types. You can leverage performance optimization and interoperability with some already available JavaScript frameworks such as Angular and React. Then added to that, you have macros available that help you extend the language.

Smart IDEs

There are many options available to make your programming journey easier. Scala IDE provides numerous editing and debugging options for development of Scala-based applications. The Scala IDE is built on top of a known Eclipse IDE. There are also plugins available to write Scala applications. We'll take a look at how to install and use IDE for Scala development in the coming sections.

Extensive language

Scala is very deep. Rich type abstractions, reflection, and macros all help you build some really powerful libraries and frameworks. Scala documentation explains everything to you: from parameterized types to reflection components. Understanding compile-time reflection (macros) and runtime reflection are essential for writing frameworks using Scala. And it's fun.

Online support

One of the biggest reasons for the growth of Scala as a programming language and its success is the vast online support available. The Scala team has put in a good amount of work and have come up with rich documentation. You can find documentation at http://docs.scala-lang.org

Learning Scala is challenging but fun. It brings out the best in you as a programmer. Isn't it fun to think and write shorter and smarter syntax with almost the same performance capabilities?

Working with Scala


In this book, we're using Scala version 2.12.2. Scala 2.12 requires your system to have Java version 8 installed. Older Scala versions support Java version 6 and above. Support for Java version 9 is still a topic of discussion for the Scala 2.13 roadmap.

Scala 2.12 was a step up from previous versions, mainly for support of Java and Scala lambda interoperability. Traits and functions are compiled directly to their Java 8 equivalents.

Java installation

Do the needful. If Java is not already installed on your machine, you may refer to Oracle's website at https://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html for instructions on how to install Java for your operating system.

SBT installation

SBT, as the name suggests, is a Simple Build Tool. From managing all source files to their compiled target versions to downloading all dependencies, SBT helps you create a Scala application with ease. You can configure how your test cases run. SBT comes with various commands for such tasks.

To install SBT on your machine, perform the following:

  1. Go to http://www.scala-sbt.org/download.html.
  2. You may choose from the available options suitable for your operating system.

After installation, you may check the version, so open a command prompt/terminal and type this:

sbt sbt-version
[info] 0.13.11

You should get the corresponding version number.

Scala REPL

There is more than one way of interacting with Scala. One of them is using Scala Interpreter (REPL). To run Scala REPL using SBT, just give the following command in the command prompt/terminal:

sbt console

This command will run Scala REPL.

To run Scala REPL using Scala binary, perform the following:

  1. Go to https://www.scala-lang.org/download/.
  2. Download the latest Scala archive.
  3. Extract the archive to any directory.
  4. Set the directory path as environment variables as shown in https://www.scala-lang.org/download/install.html.
  5. Try running the scala command, it should look something like this:

If so, congrats. You've done it. Now it's asking you to type any expression. You may try typing any expression. Try anything, like 1 + 2 or 1 + "2". REPL is your playground to learn Scala.

Scala IDEs

After getting familiar with Scala REPL, now is the time to install IDE (Integrated Development Environment). There are options available to work with Scala in IDE. Choose what fits the best for you. Eclipse lovers can go for Scala IDE. To download:

  1. Go to http://scala-ide.org/download/sdk.html.
  2. You may choose from the available options suitable for your operating system.

If you're accustomed to IntelliJ IDE, you may go for the plugin download for SBT. This will enable you to create Scala applications. To get started with Scala development on IntelliJ IDE:

  1. Go to https://www.jetbrains.com/idea/download/.
  2. You may choose from the available options suitable for your operating system.
  3. After installation, go to File | IntelliJ IDEA | Preferences | Plugins and search for Scala.
  4. Click on Install | Apply.

With this, you're ready to work with Scala on IntelliJ IDE. If you're IDE neutral, you may choose whichever suits the best. We'll use IntelliJ IDE (Community Edition) version 2017.1 with SBT version 0.13.15 and Scala 2.12.2 version.

Running our first program


 

 

Time to do some real work. The recommended way of getting started with a Scala project is to use an activator/gitor8 seed template. For gitor8, you require SBT version 0.13.13 and above. Using SBT, give the command sbt new providing the name of the template. A list of templates can be found at https://github.com/foundweekends/giter8/wiki/giter8-templates/30ac1007438f6f7727ea98c19db1f82ea8f00ac8.

For learning purposes, you may directly create a project in IntelliJ. For that, you may first start the IDE and start with a new project:

  1. Click on the Create New Project function:
  1. Select the Scala | IDEA option and click Next:
  1. Give Project name, Project location, select/locate Scala SDK, and Finish:

You're ready to write your first program.

Let's write some code:

package lsp

object First {
  def main(args: Array[String]): Unit = {
  val double: (Int => Int) = _ * 2
    (1 to 10) foreach double .andThen(println)
  }
}

The preceding program does nothing but print doubles of numbers ranging from 1 to 10. Let's go through the code. First, we gave the package declaration with a name lsp. In the next line, we created an object named First. An object in Scala is a singleton container of code which cannot take any parameters. You are not allowed to create instances of an object. Next, we used the def keyword to define the main method that works as an entry point to our application. The main method takes an array of String as parameters and returns Unit. In Scala terminology, Unit is the same as the void, it does not represent any type.

In the definition of this method, we defined a function literal and used it. A value named double is a function literal (also called anonymous function) of type Int => Int pronounced Integer to Integer. It means this anonymous function will take an integer parameter and return an integer response. An anonymous function is defined as _ * 2. Here _ (that is an underscore) is sort of syntactic sugar that infers any expected value, in our case, it's going to be an integer. This is inferred as an integer value because of the signature (Int => Int) Int to Int. This function literal applied on a range of integer values 1 to 10, represented by (1 to 10), gives back doubled values for each integer:

(1 to 10) foreach double .andThen(println)

This line contains a few tokens. Let's take them one by one. First is (1 to 10), which in Scala is a way to represent a range. It's immutable, so once produced it can't be changed. Next, foreach is used to traverse through the range. Subsequently, double is applied on each element from the range. After application of the anonymous function andThen, it composes the result of double and prints it. With this example, you successfully wrote and understood your first Scala program. Even though the code was concise, there's a bit of overhead that can be avoided. For example, the main method declaration. The code can be written as follows:

package lsp

object FirstApp extends App {
  val double: (Int => Int) = _ * 2
  (1 to 10) foreach double .andThen(print)
}

Here, the same code is written in an object that extends the App trait. By extending the App trait available, you don't have to explicitly write the main method.

Summary


This chapter was an introduction to Scala for us. We started learning about programming paradigms. After that, we discussed Scala's advantages over other available languages. Then we got our development environment ready. Finally, we wrote our first Scala program.

In the next chapter, we'll take our Scala journey ahead and learn about literals, data types, and the basic building blocks of Scala.

 

left arrow right arrow
toc Download Code

Key benefits

  • Get a grip on the functional features of the Scala programming language
  • Understand and develop optimal applications using object-oriented and functional Scala constructs
  • Learn reactive principles with Scala and work with the Akka framework

Description

Scala is a general-purpose programming language that supports both functional and object-oriented programming paradigms. Due to its concise design and versatility, Scala's applications have been extended to a wide variety of fields such as data science and cluster computing. You will learn to write highly scalable, concurrent, and testable programs to meet everyday software requirements. We will begin by understanding the language basics, syntax, core data types, literals, variables, and more. From here you will be introduced to data structures with Scala and you will learn to work with higher-order functions. Scala's powerful collections framework will help you get the best out of immutable data structures and utilize them effectively. You will then be introduced to concepts such as pattern matching, case classes, and functional programming features. From here, you will learn to work with Scala's object-oriented features. Going forward, you will learn about asynchronous and reactive programming with Scala, where you will be introduced to the Akka framework. Finally, you will learn the interoperability of Scala and Java. After reading this book, you'll be well versed with this language and its features, and you will be able to write scalable, concurrent, and reactive programs in Scala.

What you will learn

[*] Get to know the reasons for choosing Scala: its use and the advantages it provides over other languages [*] Bring together functional and object-oriented programming constructs to make a manageable application [*] Master basic to advanced Scala constructs [*] Test your applications using advanced testing methodologies such as TDD [*] Select preferred language constructs from the wide variety of constructs provided by Scala [*] Make the transition from the object-oriented paradigm to the functional programming paradigm [*] Write clean, concise, and powerful code with a functional mindset [*] Create concurrent, scalable, and reactive applications utilizing the advantages of Scala

What do you get with eBook?

Feature icon Instant access to your Digital eBook purchase
Feature icon Download this book in EPUB and PDF formats
Feature icon Access this title in our online reader with advanced features
Feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 30, 2018
Length 426 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788392822
Category :
Languages :

Table of Contents

21 Chapters
Title Page Packt Packt
Packt Upsell Packt Packt
Contributors Packt Packt
Preface Packt Packt
Getting Started with Scala Programming Packt Packt
Building Blocks of Scala Packt Packt
Shaping our Scala Program Packt Packt
Giving Meaning to Programs with Functions Packt Packt
Getting Familiar with Scala Collections Packt Packt
Object-Oriented Scala Basics Packt Packt
Next Steps in Object-Oriented Scala Packt Packt
More on Functions Packt Packt
Using Powerful Functional Constructs Packt Packt
Advanced Functional Programming Packt Packt
Working with Implicits and Exceptions Packt Packt
Introduction to Akka Packt Packt
Concurrent Programming in Scala Packt Packt
Programming with Reactive Extensions Packt Packt
Testing in Scala Packt Packt
Other Books You May Enjoy Packt Packt
Index Packt Packt

Customer reviews

filter Filter
Top Reviews
Rating distribution
star-icon star-icon star-icon star-icon star-icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Packt Packt

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Packt Packt

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Packt Packt
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Packt Packt

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Packt Packt
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Packt Packt

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.