loading

Logout succeed

Logout succeed. See you again!

ebook img

Scala Cookbook PDF

pages722 Pages
release year2013
file size16.2 MB
languageEnglish

Preview Scala Cookbook

Scala Cookbook Alvin Alexander Scala Cookbook by Alvin Alexander Copyright © 2013 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://my.safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editor: Courtney Nash Indexer: Ellen Troutman Production Editor: Rachel Steely Cover Designer: Karen Montgomery Copyeditor: Kim Cofer Interior Designer: David Futato Proofreader: Linley Dolby Illustrator: Rebecca Demarest August 2013: First Edition Revision History for the First Edition: 2013-07-30: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449339616 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Scala Cookbook, the image of a long-beaked echidna, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-33961-6 [LSI] For my mom, who loves cookbooks. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1. Testing String Equality 4 1.2. Creating Multiline Strings 6 1.3. Splitting Strings 8 1.4. Substituting Variables into Strings 9 1.5. Processing a String One Character at a Time 13 1.6. Finding Patterns in Strings 18 1.7. Replacing Patterns in Strings 21 1.8. Extracting Parts of a String That Match Patterns 22 1.9. Accessing a Character in a String 24 1.10. Add Your Own Methods to the String Class 25 2. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.1. Parsing a Number from a String 32 2.2. Converting Between Numeric Types (Casting) 36 2.3. Overriding the Default Numeric Type 37 2.4. Replacements for ++ and −− 39 2.5. Comparing Floating-Point Numbers 41 2.6. Handling Very Large Numbers 43 2.7. Generating Random Numbers 45 2.8. Creating a Range, List, or Array of Numbers 47 2.9. Formatting Numbers and Currency 49 3. Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 3.1. Looping with for and foreach 54 3.2. Using for Loops with Multiple Counters 60 3.3. Using a for Loop with Embedded if Statements (Guards) 62 3.4. Creating a for Comprehension (for/yield Combination) 63 v 3.5. Implementing break and continue 65 3.6. Using the if Construct Like a Ternary Operator 71 3.7. Using a Match Expression Like a switch Statement 72 3.8. Matching Multiple Conditions with One Case Statement 76 3.9. Assigning the Result of a Match Expression to a Variable 77 3.10. Accessing the Value of the Default Case in a Match Expression 78 3.11. Using Pattern Matching in Match Expressions 79 3.12. Using Case Classes in Match Expressions 86 3.13. Adding if Expressions (Guards) to Case Statements 87 3.14. Using a Match Expression Instead of isInstanceOf 88 3.15. Working with a List in a Match Expression 89 3.16. Matching One or More Exceptions with try/catch 91 3.17. Declaring a Variable Before Using It in a try/catch/finally Block 92 3.18. Creating Your Own Control Structures 95 4. Classes and Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 4.1. Creating a Primary Constructor 100 4.2. Controlling the Visibility of Constructor Fields 104 4.3. Defining Auxiliary Constructors 108 4.4. Defining a Private Primary Constructor 112 4.5. Providing Default Values for Constructor Parameters 114 4.6. Overriding Default Accessors and Mutators 116 4.7. Preventing Getter and Setter Methods from Being Generated 119 4.8. Assigning a Field to a Block or Function 121 4.9. Setting Uninitialized var Field Types 122 4.10. Handling Constructor Parameters When Extending a Class 124 4.11. Calling a Superclass Constructor 127 4.12. When to Use an Abstract Class 129 4.13. Defining Properties in an Abstract Base Class (or Trait) 131 4.14. Generating Boilerplate Code with Case Classes 136 4.15. Defining an equals Method (Object Equality) 140 4.16. Creating Inner Classes 143 5. Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 5.1. Controlling Method Scope 148 5.2. Calling a Method on a Superclass 152 5.3. Setting Default Values for Method Parameters 154 5.4. Using Parameter Names When Calling a Method 157 5.5. Defining a Method That Returns Multiple Items (Tuples) 159 5.6. Forcing Callers to Leave Parentheses off Accessor Methods 161 5.7. Creating Methods That Take Variable-Argument Fields 163 5.8. Declaring That a Method Can Throw an Exception 165 vi | Table of Contents 5.9. Supporting a Fluent Style of Programming 167 6. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 6.1. Object Casting 172 6.2. The Scala Equivalent of Java’s .class 174 6.3. Determining the Class of an Object 174 6.4. Launching an Application with an Object 176 6.5. Creating Singletons with object 178 6.6. Creating Static Members with Companion Objects 180 6.7. Putting Common Code in Package Objects 182 6.8. Creating Object Instances Without Using the new Keyword 185 6.9. Implement the Factory Method in Scala with apply 189 7. Packaging and Imports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 7.1. Packaging with the Curly Braces Style Notation 192 7.2. Importing One or More Members 193 7.3. Renaming Members on Import 195 7.4. Hiding a Class During the Import Process 196 7.5. Using Static Imports 197 7.6. Using Import Statements Anywhere 199 8. Traits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 8.1. Using a Trait as an Interface 203 8.2. Using Abstract and Concrete Fields in Traits 206 8.3. Using a Trait Like an Abstract Class 207 8.4. Using Traits as Simple Mixins 208 8.5. Limiting Which Classes Can Use a Trait by Inheritance 209 8.6. Marking Traits So They Can Only Be Used by Subclasses of a Certain Type 211 8.7. Ensuring a Trait Can Only Be Added to a Type That Has a Specific Method 213 8.8. Adding a Trait to an Object Instance 215 8.9. Extending a Java Interface Like a Trait 216 9. Functional Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 9.1. Using Function Literals (Anonymous Functions) 218 9.2. Using Functions as Variables 219 9.3. Defining a Method That Accepts a Simple Function Parameter 223 9.4. More Complex Functions 226 9.5. Using Closures 229 9.6. Using Partially Applied Functions 234 9.7. Creating a Function That Returns a Function 236 Table of Contents | vii 9.8. Creating Partial Functions 238 9.9. A Real-World Example 242 10. Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 10.1. Understanding the Collections Hierarchy 246 10.2. Choosing a Collection Class 250 10.3. Choosing a Collection Method to Solve a Problem 255 10.4. Understanding the Performance of Collections 261 10.5. Declaring a Type When Creating a Collection 264 10.6. Understanding Mutable Variables with Immutable Collections 265 10.7. Make Vector Your “Go To” Immutable Sequence 266 10.8. Make ArrayBuffer Your “Go To” Mutable Sequence 268 10.9. Looping over a Collection with foreach 270 10.10. Looping over a Collection with a for Loop 272 10.11. Using zipWithIndex or zip to Create Loop Counters 276 10.12. Using Iterators 278 10.13. Transforming One Collection to Another with for/yield 279 10.14. Transforming One Collection to Another with map 282 10.15. Flattening a List of Lists with flatten 285 10.16. Combining map and flatten with flatMap 286 10.17. Using filter to Filter a Collection 289 10.18. Extracting a Sequence of Elements from a Collection 291 10.19. Splitting Sequences into Subsets (groupBy, partition, etc.) 293 10.20. Walking Through a Collection with the reduce and fold Methods 295 10.21. Extracting Unique Elements from a Sequence 300 10.22. Merging Sequential Collections 302 10.23. Merging Two Sequential Collections into Pairs with zip 304 10.24. Creating a Lazy View on a Collection 306 10.25. Populating a Collection with a Range 309 10.26. Creating and Using Enumerations 311 10.27. Tuples, for When You Just Need a Bag of Things 312 10.28. Sorting a Collection 315 10.29. Converting a Collection to a String with mkString 318 11. List, Array, Map, Set (and More). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 11.1. Different Ways to Create and Populate a List 322 11.2. Creating a Mutable List 324 11.3. Adding Elements to a List 325 11.4. Deleting Elements from a List (or ListBuffer) 328 11.5. Merging (Concatenating) Lists 330 11.6. Using Stream, a Lazy Version of a List 331 11.7. Different Ways to Create and Update an Array 333 viii | Table of Contents

See more

The list of books you might like