scala cookbook

722 1.5K 1
scala cookbook

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info www.it-ebooks.info Alvin Alexander Scala Cookbook www.it-ebooks.info 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 corporate@oreilly.com. Editor: Courtney Nash Production Editor: Rachel Steely Copyeditor: Kim Cofer Proofreader: Linley Dolby Indexer: Ellen Troutman Cover Designer: Karen Montgomery Interior Designer: David Futato 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] www.it-ebooks.info For my mom, who loves cookbooks. www.it-ebooks.info www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info 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 www.it-ebooks.info [...]... recipes centered around using Scala at the command line It begins by showing tips on how to use the Scala REPL, and then shows how to use command-line tools like scalac, scala, scaladoc, and fsc It also provides recipes showing how to use Scala as a scripting language, including how to precompile your Scala scripts to make them run faster Chapter 15, Web Services, shows how to use Scala on both the client... 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. .. Software Installing Scala is simple and should just take a few minutes On Unix systems (including Mac OS X), download the software from the Scala down‐ load page to a directory on your computer like $HOME /scala, and then add these lines to your $HOME/.bash_profile file (or its equivalent, depending on which login shell you’re using): export SCALA_ HOME=/Users/Al /scala PATH=$PATH:/Users/Al /scala/ bin Once... operating system command line by executing the scala command: $ scala Welcome to Scala version 2.10.1 Type in expressions to have them evaluated Type :help for more information scala> _ Once the REPL has started, just type your expressions as input, and the REPL will evaluate them and show their output: scala> val hello = "Hello, world" hello: String = Hello, world scala> Array(1,2,3).foreach(println) 1 2... returns the remaining elements: scala> "scala" .drop(2) res0: String = ala Next, the take(2) method retains the first two elements from the collection it’s given,and discards the rest: scala> "scala" .drop(2).take(2) res1: String = al Finally, you treat the output from the take(2) method call like a String once again and call the capitalize method to get what you want: scala> "scala" .drop(2).take(2).capitalize... sequence of characters Solution In Scala, you compare two String instances with the == operator Given these strings: scala> val s1 = "Hello" s1: String = Hello 4 | Chapter 1: Strings www.it-ebooks.info scala> val s2 = "Hello" s2: String = Hello scala> val s3 = "H" + "ello" s3: String = Hello You can test their equality like this: scala> s1 == s2 res0: Boolean = true scala> s1 == s3 res1: Boolean = true... a String is null: scala> val s4: String = null s4: String = null scala> s3 == s4 res2: Boolean = false scala> s4 == s3 res3: Boolean = false If you want to compare two strings in a case-insensitive manner, you can convert both strings to uppercase or lowercase and compare them with the == method: scala> val s1 = "Hello" s1: String = Hello scala> val s2 = "hello" s2: String = hello scala> s1.toUpperCase... 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 x | Table of Contents www.it-ebooks.info... terminal window, you should have access to the scala and scalac commands at your command line You can follow a similar process if you’re using Microsoft Windows, or you can use an MSI installer See the Scala download page for more information xx | Preface www.it-ebooks.info How the Code Listings Work Most of the code listings in the book are shown in the Scala “Read-Eval-Print-Loop,” or REPL If you’ve... all of this legacy Java code; can I still use it in Scala? If so, how? • I’m starting to grok this Now I need to know, what are the top five or ten “best practices” of writing Scala code? Truthfully, I fell fast in love with everything about Scala except for one thing: the col‐ lections library seemed large and intimidating I really enjoyed using Scala so I kept using the language, but whenever I needed . 462 14.5. Compiling with scalac and Running with scala 465 14.6. Disassembling and Decompiling Scala Code 466 14.7. Finding Scala Libraries 471 14.8. Generating Documentation with scaladoc 472 14.9 www.it-ebooks.info www.it-ebooks.info Alvin Alexander Scala Cookbook www.it-ebooks.info Scala Cookbook by Alvin Alexander Copyright © 2013 Alvin Alexander. All rights reserved. Printed. Services with Scalatra 503 15.6. Replacing XML Servlet Mappings with Scalatra Mounts 507 15.7. Accessing Scalatra Web Service GET Parameters 509 15.8. Accessing POST Request Data with Scalatra 510 15.9.

Ngày đăng: 01/08/2014, 16:26

Mục lục

  • Contents of This Book

  • How the Code Listings Work

  • Conventions Used in This Book

  • How to Contact Us

  • Chapter 1. Strings

    • Introduction

      • Add Methods to Closed Classes

      • 1.4. Substituting Variables into Strings

        • Problem

        • 1.5. Processing a String One Character at a Time

          • Problem

          • 1.6. Finding Patterns in Strings

            • Problem

            • 1.7. Replacing Patterns in Strings

              • Problem

              • 1.8. Extracting Parts of a String That Match Patterns

                • Problem

                • 1.9. Accessing a Character in a String

                  • Problem

                  • 1.10. Add Your Own Methods to the String Class

                    • Problem

                    • Chapter 2. Numbers

                      • Introduction

                        • Complex Numbers and Dates

                        • 2.1. Parsing a Number from a String

                          • Problem

                          • 2.2. Converting Between Numeric Types (Casting)

                            • Problem

                            • 2.3. Overriding the Default Numeric Type

                              • Problem

                              • 2.4. Replacements for ++ and −−

                                • Problem

                                • 2.6. Handling Very Large Numbers

                                  • Problem

                                  • 2.8. Creating a Range, List, or Array of Numbers

                                    • Problem

                                    • 2.9. Formatting Numbers and Currency

                                      • Problem

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan