"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
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 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
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, 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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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?
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.
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, 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:
- Go to http://www.scala-sbt.org/download.html.
- 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.
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:
- Go to https://www.scala-lang.org/download/.
- Download the latest Scala archive.
- Extract the archive to any directory.
- Set the directory path as environment variables as shown in https://www.scala-lang.org/download/install.html.
- 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.
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:
- Go to http://scala-ide.org/download/sdk.html.
- 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:
- Go to https://www.jetbrains.com/idea/download/.
- You may choose from the available options suitable for your operating system.
- After installation, go to
File
|IntelliJ IDEA
|Preferences
|Plugins
and search forScala
. - 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.
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:
- Click on the
Create New Project
function:
- Select the
Scala
|IDEA
option and clickNext
:
- Give
Project name
,Project location
, select/locateScala SDK
, andFinish
:
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.
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.