Book description
Save time and trouble when using Scala to build object-oriented, functional, and concurrent applications. With more than 250 ready-to-use recipes and 700 code examples, this comprehensive cookbook covers the most common problems you’ll encounter when using the Scala language, libraries, and tools. It’s ideal not only for experienced Scala developers, but also for programmers learning to use this JVM language.
Author Alvin Alexander (creator of DevDaily.com) provides solutions based on his experience using Scala for highly scalable, component-based applications that support concurrency and distribution. Packed with real-world scenarios, this book provides recipes for:
- Strings, numeric types, and control structures
- Classes, methods, objects, traits, and packaging
- Functional programming in a variety of situations
- Collections covering Scala's wealth of classes and methods
- Concurrency, using the Akka Actors library
- Using the Scala REPL and the Simple Build Tool (SBT)
- Web services on both the client and server sides
- Interacting with SQL and NoSQL databases
- Best practices in Scala development
Publisher resources
Table of contents
- Scala Cookbook
- Dedication
- A Note Regarding Supplemental Files
- Preface
-
1. Strings
- Introduction
- 1.1. Testing String Equality
- 1.2. Creating Multiline Strings
- 1.3. Splitting Strings
- 1.4. Substituting Variables into Strings
- 1.5. Processing a String One Character at a Time
- 1.6. Finding Patterns in Strings
- 1.7. Replacing Patterns in Strings
- 1.8. Extracting Parts of a String That Match Patterns
- 1.9. Accessing a Character in a String
- 1.10. Add Your Own Methods to the String Class
-
2. Numbers
- Introduction
- 2.1. Parsing a Number from a String
- 2.2. Converting Between Numeric Types (Casting)
- 2.3. Overriding the Default Numeric Type
- 2.4. Replacements for ++ and −−
- 2.5. Comparing Floating-Point Numbers
- 2.6. Handling Very Large Numbers
- 2.7. Generating Random Numbers
- 2.8. Creating a Range, List, or Array of Numbers
- 2.9. Formatting Numbers and Currency
-
3. Control Structures
- Introduction
- 3.1. Looping with for and foreach
- 3.2. Using for Loops with Multiple Counters
- 3.3. Using a for Loop with Embedded if Statements (Guards)
- 3.4. Creating a for Comprehension (for/yield Combination)
- 3.5. Implementing break and continue
- 3.6. Using the if Construct Like a Ternary Operator
- 3.7. Using a Match Expression Like a switch Statement
- 3.8. Matching Multiple Conditions with One Case Statement
- 3.9. Assigning the Result of a Match Expression to a Variable
- 3.10. Accessing the Value of the Default Case in a Match Expression
- 3.11. Using Pattern Matching in Match Expressions
- 3.12. Using Case Classes in Match Expressions
- 3.13. Adding if Expressions (Guards) to Case Statements
- 3.14. Using a Match Expression Instead of isInstanceOf
- 3.15. Working with a List in a Match Expression
- 3.16. Matching One or More Exceptions with try/catch
- 3.17. Declaring a Variable Before Using It in a try/catch/finally Block
- 3.18. Creating Your Own Control Structures
-
4. Classes and Properties
- Introduction
- 4.1. Creating a Primary Constructor
- 4.2. Controlling the Visibility of Constructor Fields
- 4.3. Defining Auxiliary Constructors
- 4.4. Defining a Private Primary Constructor
- 4.5. Providing Default Values for Constructor Parameters
- 4.6. Overriding Default Accessors and Mutators
- 4.7. Preventing Getter and Setter Methods from Being Generated
- 4.8. Assigning a Field to a Block or Function
- 4.9. Setting Uninitialized var Field Types
- 4.10. Handling Constructor Parameters When Extending a Class
- 4.11. Calling a Superclass Constructor
- 4.12. When to Use an Abstract Class
- 4.13. Defining Properties in an Abstract Base Class (or Trait)
- 4.14. Generating Boilerplate Code with Case Classes
- 4.15. Defining an equals Method (Object Equality)
- 4.16. Creating Inner Classes
-
5. Methods
- Introduction
- 5.1. Controlling Method Scope
- 5.2. Calling a Method on a Superclass
- 5.3. Setting Default Values for Method Parameters
- 5.4. Using Parameter Names When Calling a Method
- 5.5. Defining a Method That Returns Multiple Items (Tuples)
- 5.6. Forcing Callers to Leave Parentheses off Accessor Methods
- 5.7. Creating Methods That Take Variable-Argument Fields
- 5.8. Declaring That a Method Can Throw an Exception
- 5.9. Supporting a Fluent Style of Programming
-
6. Objects
- Introduction
- 6.1. Object Casting
- 6.2. The Scala Equivalent of Java’s .class
- 6.3. Determining the Class of an Object
- 6.4. Launching an Application with an Object
- 6.5. Creating Singletons with object
- 6.6. Creating Static Members with Companion Objects
- 6.7. Putting Common Code in Package Objects
- 6.8. Creating Object Instances Without Using the new Keyword
- 6.9. Implement the Factory Method in Scala with apply
- 7. Packaging and Imports
-
8. Traits
- Introduction
- 8.1. Using a Trait as an Interface
- 8.2. Using Abstract and Concrete Fields in Traits
- 8.3. Using a Trait Like an Abstract Class
- 8.4. Using Traits as Simple Mixins
- 8.5. Limiting Which Classes Can Use a Trait by Inheritance
- 8.6. Marking Traits So They Can Only Be Used by Subclasses of a Certain Type
- 8.7. Ensuring a Trait Can Only Be Added to a Type That Has a Specific Method
- 8.8. Adding a Trait to an Object Instance
- 8.9. Extending a Java Interface Like a Trait
-
9. Functional Programming
- Introduction
- 9.1. Using Function Literals (Anonymous Functions)
- 9.2. Using Functions as Variables
- 9.3. Defining a Method That Accepts a Simple Function Parameter
- 9.4. More Complex Functions
- 9.5. Using Closures
- 9.6. Using Partially Applied Functions
- 9.7. Creating a Function That Returns a Function
- 9.8. Creating Partial Functions
- 9.9. A Real-World Example
-
10. Collections
- Introduction
- 10.1. Understanding the Collections Hierarchy
- 10.2. Choosing a Collection Class
- 10.3. Choosing a Collection Method to Solve a Problem
- 10.4. Understanding the Performance of Collections
- 10.5. Declaring a Type When Creating a Collection
- 10.6. Understanding Mutable Variables with Immutable Collections
- 10.7. Make Vector Your “Go To” Immutable Sequence
- 10.8. Make ArrayBuffer Your “Go To” Mutable Sequence
- 10.9. Looping over a Collection with foreach
- 10.10. Looping over a Collection with a for Loop
- 10.11. Using zipWithIndex or zip to Create Loop Counters
- 10.12. Using Iterators
- 10.13. Transforming One Collection to Another with for/yield
- 10.14. Transforming One Collection to Another with map
- 10.15. Flattening a List of Lists with flatten
- 10.16. Combining map and flatten with flatMap
- 10.17. Using filter to Filter a Collection
- 10.18. Extracting a Sequence of Elements from a Collection
- 10.19. Splitting Sequences into Subsets (groupBy, partition, etc.)
- 10.20. Walking Through a Collection with the reduce and fold Methods
- 10.21. Extracting Unique Elements from a Sequence
- 10.22. Merging Sequential Collections
- 10.23. Merging Two Sequential Collections into Pairs with zip
- 10.24. Creating a Lazy View on a Collection
- 10.25. Populating a Collection with a Range
- 10.26. Creating and Using Enumerations
- 10.27. Tuples, for When You Just Need a Bag of Things
- 10.28. Sorting a Collection
- 10.29. Converting a Collection to a String with mkString
-
11. List, Array, Map, Set (and More)
- Introduction
- 11.1. Different Ways to Create and Populate a List
- 11.2. Creating a Mutable List
- 11.3. Adding Elements to a List
- 11.4. Deleting Elements from a List (or ListBuffer)
- 11.5. Merging (Concatenating) Lists
- 11.6. Using Stream, a Lazy Version of a List
- 11.7. Different Ways to Create and Update an Array
- 11.8. Creating an Array Whose Size Can Change (ArrayBuffer)
- 11.9. Deleting Array and ArrayBuffer Elements
- 11.10. Sorting Arrays
- 11.11. Creating Multidimensional Arrays
- 11.12. Creating Maps
- 11.13. Choosing a Map Implementation
- 11.14. Adding, Updating, and Removing Elements with a Mutable Map
- 11.15. Adding, Updating, and Removing Elements with Immutable Maps
- 11.16. Accessing Map Values
- 11.17. Traversing a Map
- 11.18. Getting the Keys or Values from a Map
- 11.19. Reversing Keys and Values
- 11.20. Testing for the Existence of a Key or Value in a Map
- 11.21. Filtering a Map
- 11.22. Sorting an Existing Map by Key or Value
- 11.23. Finding the Largest Key or Value in a Map
- 11.24. Adding Elements to a Set
- 11.25. Deleting Elements from Sets
- 11.26. Using Sortable Sets
- 11.27. Using a Queue
- 11.28. Using a Stack
- 11.29. Using a Range
-
12. Files and Processes
- 12.0. Introduction
- 12.1. How to Open and Read a Text File
- 12.2. Writing Text Files
- 12.3. Reading and Writing Binary Files
- 12.4. How to Process Every Character in a Text File
- 12.5. How to Process a CSV File
- 12.6. Pretending that a String Is a File
- 12.7. Using Serialization
- 12.8. Listing Files in a Directory
- 12.9. Listing Subdirectories Beneath a Directory
- 12.10. Executing External Commands
- 12.11. Executing External Commands and Using STDOUT
- 12.12. Handling STDOUT and STDERR for External Commands
- 12.13. Building a Pipeline of Commands
- 12.14. Redirecting the STDOUT and STDIN of External Commands
- 12.15. Using AND (&&) and OR (||) with Processes
- 12.16. Handling Wildcard Characters in External Commands
- 12.17. How to Run a Process in a Different Directory
- 12.18. Setting Environment Variables When Running Commands
- 12.19. An Index of Methods to Execute External Commands
-
13. Actors and Concurrency
- Introduction
- 13.1. Getting Started with a Simple Actor
- 13.2. Creating an Actor Whose Class Constructor Requires Arguments
- 13.3. How to Communicate Between Actors
- 13.4. Understanding the Methods in the Akka Actor Lifecycle
- 13.5. Starting an Actor
- 13.6. Stopping Actors
- 13.7. Shutting Down the Akka Actor System
- 13.8. Monitoring the Death of an Actor with watch
- 13.9. Simple Concurrency with Futures
- 13.10. Sending a Message to an Actor and Waiting for a Reply
- 13.11. Switching Between Different States with become
- 13.12. Using Parallel Collections
-
14. Command-Line Tasks
- 14.0. Introduction
- 14.1. Getting Started with the Scala REPL
- 14.2. Pasting and Loading Blocks of Code into the REPL
- 14.3. Adding JAR Files and Classes to the REPL Classpath
- 14.4. Running a Shell Command from the REPL
- 14.5. Compiling with scalac and Running with scala
- 14.6. Disassembling and Decompiling Scala Code
- 14.7. Finding Scala Libraries
- 14.8. Generating Documentation with scaladoc
- 14.9. Faster Command-Line Compiling with fsc
- 14.10. Using Scala as a Scripting Language
- 14.11. Accessing Command-Line Arguments from a Script
- 14.12. Prompting for Input from a Scala Shell Script
- 14.13. Make Your Scala Scripts Run Faster
-
15. Web Services
- Introduction
- 15.1. Creating a JSON String from a Scala Object
- 15.2. Creating a JSON String from Classes That Have Collections
- 15.3. Creating a Simple Scala Object from a JSON String
- 15.4. Parsing JSON Data into an Array of Objects
- 15.5. Creating Web Services with Scalatra
- 15.6. Replacing XML Servlet Mappings with Scalatra Mounts
- 15.7. Accessing Scalatra Web Service GET Parameters
- 15.8. Accessing POST Request Data with Scalatra
- 15.9. Creating a Simple GET Request Client
- 15.10. Sending JSON Data to a POST URL
- 15.11. Getting URL Headers
- 15.12. Setting URL Headers When Sending a Request
- 15.13. Creating a GET Request Web Service with the Play Framework
- 15.14. POSTing JSON Data to a Play Framework Web Service
-
16. Databases and Persistence
- Introduction
- 16.1. Connecting to MySQL with JDBC
- 16.2. Connecting to a Database with the Spring Framework
- 16.3. Connecting to MongoDB and Inserting Data
- 16.4. Inserting Documents into MongoDB with insert, save, or +=
- 16.5. Searching a MongoDB Collection
- 16.6. Updating Documents in a MongoDB Collection
- 16.7. Accessing the MongoDB Document ID Field
- 16.8. Deleting Documents in a MongoDB Collection
- 16.9. A Quick Look at Slick
-
17. Interacting with Java
- Introduction
- 17.1. Going to and from Java Collections
- 17.2. Add Exception Annotations to Scala Methods to Work with Java
- 17.3. Using @SerialVersionUID and Other Annotations
- 17.4. Using the Spring Framework
- 17.5. Annotating varargs Methods
- 17.6. When Java Code Requires JavaBeans
- 17.7. Wrapping Traits with Implementations
-
18. The Simple Build Tool (SBT)
- Introduction
- 18.1. Creating a Project Directory Structure for SBT
- 18.2. Compiling, Running, and Packaging a Scala Project with SBT
- 18.3. Running Tests with SBT and ScalaTest
- 18.4. Managing Dependencies with SBT
- 18.5. Controlling Which Version of a Managed Dependency Is Used
- 18.6. Creating a Project with Subprojects
- 18.7. Using SBT with Eclipse
- 18.8. Generating Project API Documentation
- 18.9. Specifying a Main Class to Run
- 18.10. Using GitHub Projects as Project Dependencies
- 18.11. Telling SBT How to Find a Repository (Working with Resolvers)
- 18.12. Resolving Problems by Getting an SBT Stack Trace
- 18.13. Setting the SBT Log Level
- 18.14. Deploying a Single, Executable JAR File
- 18.15. Publishing Your Library
- 18.16. Using Build.scala Instead of build.sbt
- 18.17. Using a Maven Repository Library with SBT
- 18.18. Building a Scala Project with Ant
-
19. Types
- Introduction
- 19.1. Creating Classes That Use Generic Types
- 19.2. Creating a Method That Takes a Simple Generic Type
- 19.3. Using Duck Typing (Structural Types)
- 19.4. Make Mutable Collections Invariant
- 19.5. Make Immutable Collections Covariant
- 19.6. Create a Collection Whose Elements Are All of Some Base Type
- 19.7. Selectively Adding New Behavior to a Closed Model
- 19.8. Building Functionality with Types
- 20. Idioms
- Index
- About the Author
- Colophon
- Copyright
Product information
- Title: Scala Cookbook
- Author(s):
- Release date: August 2013
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781449339616
You might also like
book
Scala Cookbook, 2nd Edition
Save time and trouble building object-oriented, functional, and concurrent applications with Scala. The latest edition of …
book
Functional Programming in Scala
Functional Programming in Scala is a serious tutorial for programmers looking to learn FP and apply …
book
Get Programming with Scala
The perfect starting point for your journey into Scala and functional programming. In Get Programming in …
book
Functional Programming in Scala, Second Edition
This international bestseller has been revised with new exercises, annotations, and full coverage of Scala 3. …