Scala Cookbook: Recipes for Object-Oriented and Functional Programming

Scala Cookbook: Recipes for Object-Oriented and Functional Programming

by Alvin Alexander


View All Available Formats & Editions
Members save with free shipping everyday! 
See details


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 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

Product Details

ISBN-13: 9781449339616
Publisher: O'Reilly Media, Incorporated
Publication date: 08/21/2013
Pages: 722
Sales rank: 1,244,492
Product dimensions: 7.00(w) x 9.10(h) x 1.50(d)

About the Author

Alvin took the circuitous route to software development. He managed to get a degree in Aerospace Engineering from Texas A&M University, while all he was really trying to do was play baseball. Once he became a practicing engineer, he realized he liked software and programming more than engineering. So in approximate order he taught himself Fortran, C, Unix and network administration, sed, awk, Perl, Java, Python, Ruby, JRuby, Groovy, PHP, and Scala. During this process he started a software consulting firm, grew it to fifteen people, sold it, and moved to Alaska for a few years. After returning to the “Lower 48,” he self-published two books (“How I Sold My Business: A Personal Diary”, and “Zen and the Art of Consulting”). He also created, which receives millions of page views every year, and started a new software consulting business, Valley Programming.

Table of Contents

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

Customer Reviews