Learning Scala Programming
eBook - ePub

Learning Scala Programming

Vikash Sharma

Partager le livre
  1. 426 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Learning Scala Programming

Vikash Sharma

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Learning Scala Programming est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Learning Scala Programming par Vikash Sharma en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Informatique et Programmation en Java. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788391610
Édition
1

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...

Table des matiĂšres