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