Scala Cookbook, 2nd Edition

Book description

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

Publisher resources

View/Submit Errata

Table of contents

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

Product information

  • Title: Scala Cookbook, 2nd Edition
  • Author(s): Alvin Alexander
  • Release date: August 2021
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781492051541