Scala Cookbook: Recipes for Object-Oriented and Functional Programming

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Save time and trouble building object-oriented, functional, and concurrent applications with Scala. The latest edition of this comprehensive cookbook is packed with more than 250 ready-to-use recipes and 1,000 code examples to help you solve the most common problems when working with Scala 3 and its popular libraries. Scala changes the way you think about programming--and that's a good thing. Whether you're working on web, big data, or distributed applications, this cookbook provides recipes based on real-world scenarios for both experienced Scala developers and programmers just learning to use this JVM language. Author Alvin Alexander includes practical solutions from his experience using Scala for component-based, highly scalable applications that support concurrency and distribution. Recipes cover: • Strings, numbers, and control structures • Classes, methods, objects, traits, packaging, and imports • Functional programming techniques • Scala's wealth of collections classes and methods • Building and publishing Scala applications with sbt • Actors and concurrency with Scala Future and Akka Typed • Popular libraries, including Spark, Scala.js, Play Framework, and GraalVM • Types, such as variance, givens, intersections, and unions • Best practices, including pattern matching, modules, and functional error handling

Author(s): Alvin Alexander
Edition: 2
Publisher: O'Reilly Media
Year: 2021

Language: English
Commentary: Vector PDF
Pages: 802
City: Sebastopol, CA
Tags: Command Line; Programming; Java; Concurrency; Functional Programming; Apache Spark; Cookbook; Scala; Best Practices; Object-Oriented Programming; Packaging System; Akka

Copyright
Table of Contents
Preface
Conventions Used in This Book
Using Code Examples
O’Reilly Online Learning
How to Contact Us
Acknowledgments
Chapter 1. Command-Line Tasks
1.1 Getting Started with the Scala REPL
Problem
Solution
Discussion
See Also
1.2 Loading Source Code and JAR Files into the REPL
Problem
Solution
Discussion
1.3 Getting Started with the Ammonite REPL
Problem
Solution
Discussion
1.4 Compiling with scalac and Running with scala
Problem
Solution
Discussion
1.5 Disassembling and Decompiling Scala Code
Problem
Solution
Discussion
See Also
1.6 Running JAR Files with Scala and Java
Problem
Solution
Discussion
See Also
Chapter 2. Strings
2.1 Testing String Equality
Problem
Solution
Discussion
See Also
2.2 Creating Multiline Strings
Problem
Solution
Discussion
2.3 Splitting Strings
Problem
Solution
Discussion
2.4 Substituting Variables into Strings
Problem
Solution
Discussion
See Also
2.5 Formatting String Output
Problem
Solution
Discussion
See Also
2.6 Processing a String One Character at a Time
Problem
Solution
Discussion
A Complete Example
See Also
2.7 Finding Patterns in Strings
Problem
Solution
Discussion
See Also
2.8 Replacing Patterns in Strings
Problem
Solution
See Also
2.9 Extracting Parts of a String That Match Patterns
Problem
Solution
Discussion
See Also
2.10 Accessing a Character in a String
Problem
Solution
Discussion
2.11 Creating Your Own String Interpolator
Problem
Solution
Discussion
See Also
2.12 Creating Random Strings
Problem
Solution
Discussion
See Also
Chapter 3. Numbers and Dates
3.1 Parsing a Number from a String
Problem
Solution
Discussion
See Also
3.2 Converting Between Numeric Types (Casting)
Problem
Solution
Discussion
3.3 Overriding the Default Numeric Type
Problem
Solution
Discussion
3.4 Replacements for ++ and −−
Problem
Solution
Discussion
3.5 Comparing Floating-Point Numbers
Problem
Solution
Discussion
See Also
3.6 Handling Large Numbers
Problem
Solution
Discussion
See Also
3.7 Generating Random Numbers
Problem
Solution
Discussion
3.8 Formatting Numbers and Currency
Problem
Solution
Locales
Discussion
3.9 Creating New Date and Time Instances
Problem
Solution
3.10 Calculating the Difference Between Two Dates
Problem
Solution
Discussion
3.11 Formatting Dates
Problem
Solution
3.12 Parsing Strings into Dates
Problem
Solution
Chapter 4. Control Structures
for Loops and for Expressions
if/then/else-if Expressions
match Expressions and Pattern Matching
try/catch/finally Blocks
while Loops
Control Structures as a Defining Feature of Programming Languages
4.1 Looping over Data Structures with for
Problem
Solution
Discussion
See Also
4.2 Using for Loops with Multiple Counters
Problem
Solution
Discussion
See Also
4.3 Using a for Loop with Embedded if Statements (Guards)
Problem
Solution
Discussion
4.4 Creating a New Collection from an Existing Collection with for/yield
Problem
Solution
Discussion
See Also
4.5 Using the if Construct Like a Ternary Operator
Problem
Solution
Discussion
4.6 Using a Match Expression Like a switch Statement
Problem
Solution
Discussion
See Also
4.7 Matching Multiple Conditions with One Case Statement
Problem
Solution
See Also
4.8 Assigning the Result of a Match Expression to a Variable
Problem
Solution
Discussion
4.9 Accessing the Value of the Default Case in a Match Expression
Problem
Solution
Discussion
4.10 Using Pattern Matching in Match Expressions
Problem
Solution
Discussion
See Also
4.11 Using Enums and Case Classes in match Expressions
Problem
Solution
Discussion
4.12 Adding if Expressions (Guards) to Case Statements
Problem
Solution
Discussion
4.13 Using a Match Expression Instead of isInstanceOf
Problem
Solution
Discussion
See Also
4.14 Working with a List in a Match Expression
Problem
Solution
Discussion
See Also
4.15 Matching One or More Exceptions with try/catch
Problem
Solution
Discussion
See Also
4.16 Declaring a Variable Before Using It in a try/catch/finally Block
Problem
Solution
Discussion
See Also
4.17 Creating Your Own Control Structures
Problem
Solution
Discussion
See Also
Chapter 5. Classes
Classes and Case Classes
5.1 Choosing from Domain Modeling Options
Problem
Solution
Discussion
See Also
5.2 Creating a Primary Constructor
Problem
Solution
Discussion
5.3 Controlling the Visibility of Constructor Fields
Problem
Solution
Discussion
See Also
5.4 Defining Auxiliary Constructors for Classes
Problem
Solution
Discussion
5.5 Defining a Private Primary Constructor
Problem
Solution
Discussion
5.6 Providing Default Values for Constructor Parameters
Problem
Solution
Discussion
5.7 Handling Constructor Parameters When Extending a Class
Problem
Solution
Discussion
5.8 Calling a Superclass Constructor
Problem
Solution
Discussion
5.9 Defining an equals Method (Object Equality)
Problem
Solution
Discussion
See Also
5.10 Preventing Accessor and Mutator Methods from Being Generated
Problem
Solution
Discussion
5.11 Overriding Default Accessors and Mutators
Problem
Solution
Discussion
5.12 Assigning a Block or Function to a (lazy) Field
Problem
Solution
Discussion
See Also
5.13 Setting Uninitialized var Field Types
Problem
Solution
Discussion
See Also
5.14 Generating Boilerplate Code with Case Classes
Problem
Solution
Discussion
See Also
5.15 Defining Auxiliary Constructors for Case Classes
Problem
Solution
See Also
Chapter 6. Traits and Enums
6.1 Using a Trait as an Interface
Problem
Solution
Discussion
See Also
6.2 Defining Abstract Fields in Traits
Problem
Solution
Discussion
See Also
6.3 Using a Trait Like an Abstract Class
Problem
Solution
Discussion
See Also
6.4 Using Traits as Mixins
Problem
Solution
Discussion
See Also
6.5 Resolving Method Name Conflicts and Understanding super
Problem
Solution
Discussion
See Also
6.6 Marking Traits So They Can Only Be Used by Subclasses of a Certain Type
Problem
Solution
Discussion
See Also
6.7 Ensuring a Trait Can Only Be Added to a Type That Has a Specific Method
Problem
Solution
Discussion
6.8 Limiting Which Classes Can Use a Trait by Inheritance
Problem
Solution
Discussion
6.9 Working with Parameterized Traits
Problem
Solution
Discussion
6.10 Using Trait Parameters
Problem
Solution
Discussion
6.11 Using Traits to Create Modules
Problem
Solution
Discussion
See Also
6.12 How to Create Sets of Named Values with Enums
Problem
Solution
Discussion
See Also
6.13 Modeling Algebraic Data Types with Enums
Problem
Solution
Discussion
See Also
Chapter 7. Objects
7.1 Casting Objects
Problem
Solution
Discussion
7.2 Passing a Class Type with the classOf Method
Problem
Solution
Discussion
See Also
7.3 Creating Singletons with object
Problem
Solution
Discussion
See Also
7.4 Creating Static Members with Companion Objects
Problem
Solution
Discussion
See Also
7.5 Using apply Methods in Objects as Constructors
Problem
Solution
Discussion
See Also
7.6 Implementing a Static Factory with apply
Problem
Solution
Discussion
See Also
7.7 Reifying Traits as Objects
Problem
Solution
Discussion
See Also
7.8 Implementing Pattern Matching with unapply
Problem
Solution
See Also
Chapter 8. Methods
8.1 Controlling Method Scope (Access Modifiers)
Problem
Solution
Discussion
8.2 Calling a Method on a Superclass or Trait
Problem
Solution
8.3 Using Parameter Names When Calling a Method
Problem
Solution
Discussion
8.4 Setting Default Values for Method Parameters
Problem
Solution
Discussion
8.5 Creating Methods That Take Variable-Argument Fields
Problem
Solution
Discussion
8.6 Forcing Callers to Leave Parentheses Off Accessor Methods
Problem
Solution
Discussion
See Also
8.7 Declaring That a Method Can Throw an Exception
Problem
Solution
Discussion
See Also
8.8 Supporting a Fluent Style of Programming
Problem
Solution
Discussion
See Also
8.9 Adding New Methods to Closed Classes with Extension Methods
Problem
Solution
Discussion
See Also
Chapter 9. Packaging and Imports
9.1 Packaging with the Curly Braces Style Notation
Problem
Solution
Discussion
9.2 Importing One or More Members
Problem
Solution
Discussion
9.3 Renaming Members on Import
Problem
Solution
Discussion
9.4 Hiding a Class During the Import Process
Problem
Solution
Discussion
9.5 Importing Static Members
Problem
Solution
Discussion
9.6 Using Import Statements Anywhere
Problem
Solution
Discussion
9.7 Importing Givens
Problem
Solution
Discussion
See Also
Chapter 10. Functional Programming
10.1 Using Function Literals (Anonymous Functions)
Problem
Solution
Discussion
See Also
10.2 Passing Functions Around as Variables
Problem
Solution
Discussion
See Also
10.3 Defining a Method That Accepts a Simple Function Parameter
Problem
Solution
Discussion
See Also
10.4 Declaring More Complex Higher-Order Functions
Problem
Solution
Discussion
See Also
10.5 Using Partially Applied Functions
Problem
Solution
Discussion
10.6 Creating a Method That Returns a Function
Problem
Solution
Discussion
10.7 Creating Partial Functions
Problem
Solution
Discussion
See Also
10.8 Implementing Functional Error Handling
Problem
Solution
Discussion
See Also
10.9 Real-World Example: Passing Functions Around in an Algorithm
10.10 Real-World Example: Functional Domain Modeling
The Data Model
Functions That Operate on That Model
Use Traits To Create a Dependency Injection Framework
See Also
Chapter 11. Collections: Introduction
Understanding the Collections Hierarchy
The Collections Are Deep and Wide
11.1 Choosing a Collections Class
Problem
Solution
See Also
11.2 Understanding the Performance of Collections
Problem
Solution
Discussion
See Also
11.3 Understanding Mutable Variables with Immutable Collections
Problem
Solution
Discussion
11.4 Creating a Lazy View on a Collection
Problem
Solution
Discussion
Chapter 12. Collections: Common Sequence Classes
12.1 Making Vector Your Go-To Immutable Sequence
Problem
Solution
Discussion
12.2 Creating and Populating a List
Problem
Solution
Discussion
See Also
12.3 Adding Elements to a List
Problem
Solution
Discussion
See Also
12.4 Deleting Elements from a List (or ListBuffer)
Problem
Solution
Discussion
See Also
12.5 Creating a Mutable List with ListBuffer
Problem
Solution
Discussion
12.6 Using LazyList, a Lazy Version of a List
Problem
Solution
Discussion
See Also
12.7 Making ArrayBuffer Your Go-To Mutable Sequence
Problem
Solution
Discussion
12.8 Deleting Array and ArrayBuffer Elements
Problem
Solution
Discussion
12.9 Creating and Updating an Array
Problem
Solution
Discussion
See Also
12.10 Creating Multidimensional Arrays
Problem
Solution
Discussion
12.11 Sorting Arrays
Problem
Solution
Discussion
See Also
Chapter 13. Collections: Common Sequence Methods
Predicate
Anonymous Functions
Implied Loops
Recipes in This Chapter
13.1 Choosing a Collection Method to Solve a Problem
Problem
Solution
Discussion
13.2 Looping Over a Collection with foreach
Problem
Solution
Discussion
See Also
13.3 Using Iterators
Problem
Solution
Discussion
See Also
13.4 Using zipWithIndex or zip to Create Loop Counters
Problem
Solution
Discussion
13.5 Transforming One Collection to Another with map
Problem
Solution
Discussion
13.6 Flattening a List of Lists with flatten
Problem
Solution
Discussion
13.7 Using filter to Filter a Collection
Problem
Solution
Discussion
13.8 Extracting a Sequence of Elements from a Collection
Problem
Solution
Discussion
13.9 Splitting Sequences into Subsets
Problem
Solution
Discussion
13.10 Walking Through a Collection with the reduce and fold Methods
Problem
Solution
Discussion
See Also
13.11 Finding the Unique Elements in a Sequence
Problem
Solution
Discussion
13.12 Merging Sequential Collections
Problem
Solution
Discussion
13.13 Randomizing a Sequence
Problem
Solution
Discussion
13.14 Sorting a Collection
Problem
Solution
Discussion
See Also
13.15 Converting a Collection to a String with mkString and addString
Problem
Solution
Discussion
Chapter 14. Collections: Using Maps
14.1 Creating and Using Maps
Problem
Solution
Discussion
14.2 Choosing a Map Implementation
Problem
Solution
Discussion
See Also
14.3 Adding, Updating, and Removing Immutable Map Elements
Problem
Solution
Discussion
14.4 Adding, Updating, and Removing Elements in Mutable Maps
Problem
Solution
Discussion
14.5 Accessing Map Values (Without Exceptions)
Problem
Solution
14.6 Testing for the Existence of a Key or Value in a Map
Problem
Solution
Discussion
See Also
14.7 Getting the Keys or Values from a Map
Problem
Solution
Discussion
14.8 Finding the Largest (or Smallest) Key or Value in a Map
Problem
Solution
Discussion
See Also
14.9 Traversing a Map
Problem
Solution
Discussion
14.10 Sorting an Existing Map by Key or Value
Problem
Solution
Discussion
14.11 Filtering a Map
Problem
Solution
Discussion
Chapter 15. Collections: Tuple, Range, Set, Stack, and Queue
15.1 Creating Heterogeneous Lists with Tuples
Problem
Solution
Discussion
See Also
15.2 Creating Ranges
Problem
Solution
Discussion
15.3 Creating a Set and Adding Elements to It
Problem
Solution
15.4 Deleting Elements from Sets
Problem
Solution
15.5 Storing Values in a Set in Sorted Order
Problem
Solution
Discussion
See Also
15.6 Creating and Using a Stack
Problem
Solution
Discussion
15.7 Creating and Using a Queue
Problem
Solution
Discussion
Chapter 16. Files and Processes
16.1 Reading Text Files
Problem
Solution
Discussion
See Also
16.2 Writing Text Files
Problem
Solution
Discussion
See Also
16.3 Reading and Writing Binary Files
Problem
Solution
Discussion
See Also
16.4 Pretending That a String Is a File
Problem
Solution
Discussion
16.5 Serializing and Deserializing Objects to Files
Problem
Solution
Discussion
16.6 Listing Files in a Directory
Problem
Solution
Discussion
See Also
16.7 Executing External Commands
Problem
Solution
Discussion
16.8 Executing External Commands and Reading Their STDOUT
Problem
Solution
16.9 Handling Both STDOUT and STDERR of Commands
Problem
Solution
Discussion
See Also
16.10 Building a Pipeline of External Commands
Problem
Solution
Discussion
Chapter 17. Building Projects with sbt
17.1 Creating a Project Directory Structure for sbt
Problem
Solution
Discussion
17.2 Building Projects with the sbt Command
Problem
Solution
Discussion
17.3 Understanding build.sbt Syntax Styles
Problem
Solution
Discussion
17.4 Compiling, Running, and Packaging a Scala Project
Problem
Solution
Discussion
17.5 Understanding Other sbt Commands
Problem
Solution
Discussion
See Also
17.6 Continuous Compiling and Testing
Problem
Solution
17.7 Managing Dependencies with sbt
Problem
Solution
Discussion
17.8 Controlling Which Version of a Managed Dependency Is Used
Problem
Solution
Discussion
See Also
17.9 Generating Project API Documentation
Problem
Solution
Discussion
See Also
17.10 Specifying a Main Class to Run with sbt
Problem
Solution
Discussion
See Also
17.11 Deploying a Single Executable JAR File
Problem
Solution
Discussion
See Also
17.12 Publishing Your Library
Problem
Solution
Discussion
See Also
Chapter 18. Concurrency with Scala Futures and Akka Actors
18.1 Creating a Future
Problem
Solution
Discussion
See Also
18.2 Using Callback and Transformation Methods with Futures
Problem
Solution
Discussion
18.3 Writing Methods That Return Futures
Problem
Solution
Discussion
18.4 Running Multiple Futures in Parallel
Problem
Solution
Discussion
18.5 Creating OOP-Style Actors
Problem
Solution
Discussion
18.6 Creating FP-Style Actors
Problem
Solution
Discussion
18.7 Sending Messages to Actors
Problem
Solution
Discussion
See Also
18.8 Creating Actors That Have Multiple States (FSM)
Problem
Solution
Discussion
Chapter 19. Play Framework and Web Services
19.1 Creating a Play Framework Project
Problem
Solution
Discussion
See Also
19.2 Creating a New Play Framework Endpoint
Problem
Solution
Discussion
See Also
19.3 Returning JSON from a GET Request with Play
Problem
Solution
Discussion
See Also
19.4 Serializing a Scala Object to a JSON String
Problem
Solution
Discussion
19.5 Deserializing JSON into a Scala Object
Problem
Solution
Discussion
See Also
19.6 Using the Play JSON Library Outside of the Play Framework
Problem
Solution
Discussion
19.7 Using the sttp HTTP Client
Problem
Solution
Discussion
Chapter 20. Apache Spark
20.1 Getting Started with Spark
Problem
Solution
Discussion
See Also
20.2 Reading a File into a Spark RDD
Problem
Solution
Discussion
See Also
20.3 Reading a CSV File into a Spark RDD
Problem
Solution
Discussion
20.4 Using Spark Like a Database with DataFrames
Problem
Solution
Discussion
See Also
20.5 Reading Data Files into a Spark DataFrame
Problem
Solution
Discussion
20.6 Using Spark SQL Queries Against Multiple Files
Problem
Solution
Discussion
See Also
20.7 Creating a Spark Batch Application
Problem
Solution
Discussion
See Also
Chapter 21. Scala.js, GraalVM, and jpackage
21.1 Getting Started with Scala.js
Problem
Solution
Discussion
See Also
21.2 Responding to Events with Scala.js
Problem
Solution
Discussion
See Also
21.3 Building Single-Page Applications with Scala.js
Problem
Solution
Discussion
See Also
21.4 Building Native Executables with GraalVM
Problem
Solution
Discussion
See Also
21.5 Bundling Your Application with jpackage
Problem
Solution
Discussion
See Also
Chapter 22. Integrating Scala with Java
22.1 Using Java Collections in Scala
Problem
Solution
Discussion
See Also
22.2 Using Scala Collections in Java
Problem
Solution
Discussion
See Also
22.3 Using Java Optional Values in Scala
Problem
Solution
Discussion
See Also
22.4 Using Scala Option Values in Java
Problem
Solution
Discussion
See Also
22.5 Using Scala Traits in Java
Problem
Solution
Discussion
22.6 Using Java Interfaces in Scala
Problem
Solution
Discussion
22.7 Adding Exception Annotations to Scala Methods
Problem
Solution
Discussion
See Also
22.8 Annotating varargs Methods to Work with Java
Problem
Solution
Discussion
22.9 Using @SerialVersionUID and Other Annotations
Problem
Solution
Discussion
See Also
Chapter 23. Types
23.1 Creating a Method That Takes a Simple Generic Type
Problem
Solution
Discussion
23.2 Creating Classes That Use Simple Generic Types
Problem
Solution
Discussion
See Also
23.3 Making Immutable Generic Parameters Covariant
Problem
Solution
Discussion
23.4 Creating a Class Whose Generic Elements Can Be Mutated
Problem
Solution
Discussion
See Also
23.5 Creating a Class Whose Parameters Implement a Base Type
Problem
Solution
Discussion
23.6 Using Duck Typing (Structural Types)
Problem
Solution
Discussion
23.7 Creating Meaningful Type Names with Opaque Types
Problem
Solution
Discussion
23.8 Using Term Inference with given and using
Problem
Solution
Discussion
See Also
23.9 Simulating Dynamic Typing with Union Types
Problem
Solution
Discussion
See Also
23.10 Declaring That a Value Is a Combination of Types
Problem
Solution
Discussion
See Also
23.11 Controlling How Classes Can Be Compared with Multiversal Equality
Problem
Solution
Discussion
23.12 Limiting Equality Comparisons with the CanEqual Typeclass
Problem
Solution
Discussion
Chapter 24. Best Practices
24.1 Writing Pure Functions
Problem
Solution
Discussion
24.2 Using Immutable Variables and Collections
Problem
Solution
Discussion
24.3 Writing Expressions (Instead of Statements)
Problem
Solution
Discussion
See Also
24.4 Using Match Expressions and Pattern Matching
Problem
Solution
See Also
24.5 Eliminating null Values from Your Code
Problem
Solution
Discussion
See Also
24.6 Using Scala’s Error-Handling Types (Option, Try, and Either)
Problem
Solution
Discussion
See Also
24.7 Building Modular Systems
Problem
Solution
Discussion
24.8 Handling Option Values with Higher-Order Functions
Problem
Solution
Discussion
See Also
Index
About the Author