Learning Scala Programming
eBook - ePub

Learning Scala Programming

Vikash Sharma

Condividi libro
  1. 426 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Learning Scala Programming

Vikash Sharma

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Learn how to write scalable and concurrent programs in Scala, a language that grows with you.About This Book• 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 frameworkWho This Book Is ForThis book is for programmers who choose to get a grip over Scala to write concurrent, scalable, and reactive programs. No prior experience with any programming language is required to learn the concepts explained in this book. Knowledge of any programming language would help the reader understanding concepts faster though.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 ScalaIn DetailScala 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.Style and approachThis book is for programmers who want to master Scala to write concurrent, scalable, and reactive programs. Though no experience with any programming language is needed, some basic knowledge would help understand concepts faster.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Learning Scala Programming è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Learning Scala Programming di Vikash Sharma in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatique e Programmation en Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788391610
Edizione
1
Argomento
Informatique

Getting Familiar with Scala Collections

"The code that you write should absorb more meaning without becoming bloated or losing comprehensibility."
- Anonymous
In any programming language, one of the essential requirements is to have a way of working with a set of data, or, in other words, a collection of data. If you have worked with any programming language, you must already know the importance of its collection framework. Scala has a rich variety of collections; a rich set of helper functions makes it a lot easier to work with any Scala collection. In this chapter, we'll go through all the essentials of Scala collections. We'll be able to distinguish between several collection options, and also make efficient use of all collections. Along the way, we'll learn about:
  • Immutable and mutable Scala collections
  • Scala's collection hierarchy
  • Commonly used collections in Scala
  • Rich operations performed on collections
  • Parallel collections
  • Conversion from a Java to a Scala collection
  • Choosing a collection
  • Collection performance

Motivation

Before we start learning about immutable and mutable collections in Scala, we'll try to solve a simple problem using powerful methods provided by Scala collections. For that, let's take a look at a scenario:
RESTful APIs
As shown in the preceding image, we have a set of APIs with method types such as GET, POST, and PUT, and their associated URIs. As these are two entities (method and URI), think of all these as a list of tuples. Now we want to segregate them, so we can create a map, as shown in the right column of the preceding image. A map is a collection that stores values in a key-value pair. Hence, on the right side you can see API information as key-value pairs, where key is the method name, and the value is a list of URIs for that particular request type. So, the idea is to convert List[(String, String)] to Map[String, List[String]]. You may want to think about the solution, and come up with your own.
Meanwhile, let's see if Scala helps us in any way with our solution:
object RESTFulAPIs extends App { //List of Method and URI val listOfAPIs = List(("GET", "/user/:id"), ("GET", "user/:id/profile/:p_id"), ("POST", "/user"), ("POST", "/profile"), ("PUT", "/user/:id")) /* * Returns a scala.collection.immutable.Map[String, List[(String,String)]] */ val groupedListOfAPIs = listOfAPIs.groupBy(_._1) println(s"APIs grouped to a Map :: $groupedListOfAPIs") /* * Returns a scala.collection.immutable.Map[String, List[String]] */ val apisByMethod = groupedListOfAPIs.mapValues(_.map(_._2)) println(s"APIs By Method :: $apisByMethod") } 
Here's the result:
APIs grouped to a Map :: Map(POST -> List((POST,/user), (POST,/profile)), GET -> List((GET,/user/:id), (GET,user/:id/profile/:p_id)), PUT -> List((PUT,/user/:id))) APIs By Method :: Map(POST -> List(/user, /profile), GET -> List(/user/:id, user/:id/profile/:p_id), PUT -> List(/user/:id)) 
If you have come up with a set of for loops or recursive methods to accomplish what can be done using a single method, you may want to rethink, or take a look at the solution we have here. Here, we used two utility methods that fulfill our purpose. The first one is groupBy, defined in the TraversableLike trait, which converts our List[(String, String)] to a Map[String, List[String]] grouped by the first element of the tuple, the method names. This groupBy operation gives us this:
Map(POST -> List((POST,/user), (POST,/profile)), GET -> List((GET,/user/:id), (GET,user/:id/profile/:p_id)), PUT -> List((PUT,/user/:id))) 
The latter is the mapValues method from MapLike trait, which is used to wrap the given map with the same key. The value for each key is simply f(this(key)):
def mapValues[W](f: V => W): Map[K, W] 
These two methods were enough to provide the solution, and helped us avoid many traversals using loops. This is just one example, and a lot can be done within only few lines of code that would otherwise have taken several lines. This really makes Scala collections powerful. Scala's collection framework is easy to use; most of the helper methods are universal, with a few exceptions. Also, there is no compromise with performance; these are performance-tuned methods. One can rely on these methods to accomplish any logic; it makes your code look nicer. But that's not all, it's just the beginning. Usually, collections are prone to code that is written with the current environment in mind. That usually makes it hard to debug what went wrong, specifically when mutable collections are in place. So, just to remove this complication, Scala has these immutable data collections. Once created, the immutable collections can't be updated. But how do they work, and how are they different from mutable collections? Let's go through and try to understand.

Immutable and mutable collections

A collection is used to contain data that is used by the program later in time. In a multithreaded environment, if multiple threads try to access a collection at the same time, this can give you a hard time debugging what went wrong. That is a problem programmers usually face when working with collections in a multithreaded environment. But there's a universal solution for that, which expects you to use an immutable collection. Immutable means you can't change/mutate it. Scala provides you options to choose from: root, mutable, and immutable collections. These three are variants that exist in three separate packages: scala.collection, scala.collection.mutable, and scala.collection.immutable. If you don't specify the collection and use one, it'll be an immutable one by default. But how do these work, exactly? Let's take a look:
scala> val studentsPresent = List("Alex", "Bob", "Chris") studentsPresent: List[String] = List(Alex, Bob, Chris) 
A collection that does not allow us to update or delete its elements is of not much use. So, why do we say these are rich collections? The reason is that even though these are immutable collections, there are ways to add and remove elements, but these actions return a new collection altogether. We'll see how these are constructed and then how adding an element affects the collection later in this chapter; but for now, it's important to know that immutable collections can be updated, although doing so returns another collection with the same set of elements, along with the updated collection.
On the other hand, we have mutable collections, which work similar to most object-oriented programming languages. You can declare and instantiate a collection with a few elements. Then, based on any requirements afterwards, you can change its elements, or remove them. With these mutable collections, Scala gives you a choice to make when selecting a collection to work with. When you use mutable collections, you get an extra set of methods to mutate the collection. Be sure, though, about the instances where you may mutate collections. That'll make your program world free of mutability complications.
The third variant, root collections, resides in the scala.collection package. When you use a root collection, it can be mutable or immutable. What does that mean? It means that a particular collection is a superclass of a collection from the same family residing in both the scala.collection.mutable and scala.collection.immutable packages. To understand what we just said, take a look at the following method:
def afunction(xs: scala.collection.Iterable[String]) = ??? 
The afunction function can take both mutable and immutable collections, as long as they are Iterable, which is one of the traits available in Scala's collection hierarchy.
There are few extra methods that let you mutate your collection, and as we may expect, those are defined only for collections in the scala.collection.mutable package, not the scala.collection or scala.collection.immutable packages. In that case, it's clear that while writing your root collection, the Scala compiler is not going to allow you to update your collection. We talked about one of the use cases of root collections where, regardless of the type of your collection, you can define a function—that i...

Indice dei contenuti