ebook img

Scala Cookbook: Recipes for Object-Oriented and Functional Programming PDF

802 Pages·2021·10.508 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Scala Cookbook: Recipes for Object-Oriented and Functional Programming

SECOND EDITION Scala Cookbook Recipes for Object-Oriented and Functional Programming Alvin Alexander Scala Cookbook by Alvin Alexander Copyright © 2021 Alvin Alexander. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Suzanne McQuade Indexer: Potomac Indexing, LLC Development Editor: Jeff Bleiel Interior Designer: David Futato Production Editor: Christopher Faucher Cover Designer: Karen Montgomery Copyeditor: JM Olejarz Illustrator: Kate Dullea Proofreader: Athena Lakri August 2013: First Edition August 2021: Second Edition Revision History for the Second Edition 2021-08-09: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492051541 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Scala Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-05154-1 [LSI] To the Kirn family of Louisville, Kentucky. As in the movie, While You Were Sleeping, I adopted them a long time ago, and my life has never been the same. And also to my friends who passed away during the creation of this book: Frank, Ben, Kenny, Bill, and Lori. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Command-Line Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Getting Started with the Scala REPL 3 1.2 Loading Source Code and JAR Files into the REPL 6 1.3 Getting Started with the Ammonite REPL 8 1.4 Compiling with scalac and Running with scala 11 1.5 Disassembling and Decompiling Scala Code 13 1.6 Running JAR Files with Scala and Java 17 2. Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.1 Testing String Equality 24 2.2 Creating Multiline Strings 26 2.3 Splitting Strings 27 2.4 Substituting Variables into Strings 29 2.5 Formatting String Output 32 2.6 Processing a String One Character at a Time 36 2.7 Finding Patterns in Strings 41 2.8 Replacing Patterns in Strings 43 2.9 Extracting Parts of a String That Match Patterns 44 2.10 Accessing a Character in a String 46 2.11 Creating Your Own String Interpolator 47 2.12 Creating Random Strings 50 v 3. Numbers and Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 3.1 Parsing a Number from a String 56 3.2 Converting Between Numeric Types (Casting) 59 3.3 Overriding the Default Numeric Type 62 3.4 Replacements for ++ and −− 64 3.5 Comparing Floating-Point Numbers 65 3.6 Handling Large Numbers 67 3.7 Generating Random Numbers 69 3.8 Formatting Numbers and Currency 71 3.9 Creating New Date and Time Instances 76 3.10 Calculating the Difference Between Two Dates 78 3.11 Formatting Dates 80 3.12 Parsing Strings into Dates 82 4. Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 4.1 Looping over Data Structures with for 88 4.2 Using for Loops with Multiple Counters 92 4.3 Using a for Loop with Embedded if Statements (Guards) 93 4.4 Creating a New Collection from an Existing Collection with for/yield 95 4.5 Using the if Construct Like a Ternary Operator 97 4.6 Using a Match Expression Like a switch Statement 98 4.7 Matching Multiple Conditions with One Case Statement 102 4.8 Assigning the Result of a Match Expression to a Variable 103 4.9 Accessing the Value of the Default Case in a Match Expression 104 4.10 Using Pattern Matching in Match Expressions 105 4.11 Using Enums and Case Classes in match Expressions 111 4.12 Adding if Expressions (Guards) to Case Statements 112 4.13 Using a Match Expression Instead of isInstanceOf 114 4.14 Working with a List in a Match Expression 117 4.15 Matching One or More Exceptions with try/catch 120 4.16 Declaring a Variable Before Using It in a try/catch/finally Block 123 4.17 Creating Your Own Control Structures 125 5. Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 5.1 Choosing from Domain Modeling Options 131 5.2 Creating a Primary Constructor 137 5.3 Controlling the Visibility of Constructor Fields 140 5.4 Defining Auxiliary Constructors for Classes 144 5.5 Defining a Private Primary Constructor 146 vi | Table of Contents 5.6 Providing Default Values for Constructor Parameters 148 5.7 Handling Constructor Parameters When Extending a Class 149 5.8 Calling a Superclass Constructor 152 5.9 Defining an equals Method (Object Equality) 154 5.10 Preventing Accessor and Mutator Methods from Being Generated 162 5.11 Overriding Default Accessors and Mutators 165 5.12 Assigning a Block or Function to a (lazy) Field 167 5.13 Setting Uninitialized var Field Types 169 5.14 Generating Boilerplate Code with Case Classes 171 5.15 Defining Auxiliary Constructors for Case Classes 176 6. Traits and Enums. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 6.1 Using a Trait as an Interface 181 6.2 Defining Abstract Fields in Traits 183 6.3 Using a Trait Like an Abstract Class 185 6.4 Using Traits as Mixins 186 6.5 Resolving Method Name Conflicts and Understanding super 189 6.6 Marking Traits So They Can Only Be Used by Subclasses of a Certain Type 192 6.7 Ensuring a Trait Can Only Be Added to a Type That Has a Specific Method 196 6.8 Limiting Which Classes Can Use a Trait by Inheritance 197 6.9 Working with Parameterized Traits 198 6.10 Using Trait Parameters 200 6.11 Using Traits to Create Modules 204 6.12 How to Create Sets of Named Values with Enums 210 6.13 Modeling Algebraic Data Types with Enums 213 7. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 7.1 Casting Objects 218 7.2 Passing a Class Type with the classOf Method 219 7.3 Creating Singletons with object 220 7.4 Creating Static Members with Companion Objects 221 7.5 Using apply Methods in Objects as Constructors 223 7.6 Implementing a Static Factory with apply 225 7.7 Reifying Traits as Objects 227 7.8 Implementing Pattern Matching with unapply 230 8. Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 8.1 Controlling Method Scope (Access Modifiers) 235 Table of Contents | vii 8.2 Calling a Method on a Superclass or Trait 239 8.3 Using Parameter Names When Calling a Method 242 8.4 Setting Default Values for Method Parameters 244 8.5 Creating Methods That Take Variable-Argument Fields 245 8.6 Forcing Callers to Leave Parentheses Off Accessor Methods 247 8.7 Declaring That a Method Can Throw an Exception 248 8.8 Supporting a Fluent Style of Programming 250 8.9 Adding New Methods to Closed Classes with Extension Methods 253 9. Packaging and Imports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 9.1 Packaging with the Curly Braces Style Notation 256 9.2 Importing One or More Members 258 9.3 Renaming Members on Import 259 9.4 Hiding a Class During the Import Process 261 9.5 Importing Static Members 263 9.6 Using Import Statements Anywhere 264 9.7 Importing Givens 267 10. Functional Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 10.1 Using Function Literals (Anonymous Functions) 279 10.2 Passing Functions Around as Variables 281 10.3 Defining a Method That Accepts a Simple Function Parameter 287 10.4 Declaring More Complex Higher-Order Functions 289 10.5 Using Partially Applied Functions 292 10.6 Creating a Method That Returns a Function 295 10.7 Creating Partial Functions 298 10.8 Implementing Functional Error Handling 303 10.9 Real-World Example: Passing Functions Around in an Algorithm 305 10.10 Real-World Example: Functional Domain Modeling 308 11. Collections: Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 11.1 Choosing a Collections Class 324 11.2 Understanding the Performance of Collections 330 11.3 Understanding Mutable Variables with Immutable Collections 333 11.4 Creating a Lazy View on a Collection 335 12. Collections: Common Sequence Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 12.1 Making Vector Your Go-To Immutable Sequence 341 12.2 Creating and Populating a List 344 viii | Table of Contents

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.