O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Scala Cookbook

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

Table of Contents

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