Book Image

Learning Scala Programming

By : Vikash Sharma
Book Image

Learning Scala Programming

By: Vikash Sharma

Overview of this book

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.
Table of Contents (21 chapters)
Title Page
Packt Upsell
Contributors
Preface
Index

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?