Scala Cookbook Recipes for Object-Oriented and Functional Programming (Alvin Alexander) (Z-Library)

Author: Alvin Alexander

技术

Save time and trouble building object-oriented, functional, and concurrent applications with Scala. The latest edition of this comprehensive cookbook is packed with more than 250 ready-to-use recipes and 1,000 code examples to help you solve the most common problems when working with Scala 3 and its popular libraries. Scala changes the way you think about programming--and that's a good thing. Whether you're working on web, big data, or distributed applications, this cookbook provides recipes based on real-world scenarios for both experienced Scala developers and programmers just learning to use this JVM language. Author Alvin Alexander includes practical solutions from his experience using Scala for component-based, highly scalable applications that support concurrency and distribution. Recipes cover: • Strings, numbers, and control structures • Classes, methods, objects, traits, packaging, and imports • Functional programming techniques • Scala's wealth of collections classes and methods • Building and publishing Scala applications with sbt • Actors and concurrency with Scala Future and Akka Typed • Popular libraries, including Spark, Scala.js, Play Framework, and GraalVM • Types, such as variance, givens, intersections, and unions • Best practices, including pattern matching, modules, and functional error handling

📄 File Format: PDF
💾 File Size: 10.5 MB
68
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
(This page has no text content)
📄 Page 3
Alvin Alexander Scala Cookbook Recipes for Object-Oriented and Functional Programming SECOND EDITION
📄 Page 4
978-1-492-05154-1 [LSI] 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 corporate@oreilly.com. Acquisitions Editor: Suzanne McQuade Development Editor: Jeff Bleiel Production Editor: Christopher Faucher Copyeditor: JM Olejarz Proofreader: Athena Lakri Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea 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.
📄 Page 5
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.
📄 Page 6
(This page has no text content)
📄 Page 7
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
📄 Page 8
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
📄 Page 9
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
📄 Page 10
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
📄 Page 11
12.3 Adding Elements to a List 346 12.4 Deleting Elements from a List (or ListBuffer) 349 12.5 Creating a Mutable List with ListBuffer 351 12.6 Using LazyList, a Lazy Version of a List 352 12.7 Making ArrayBuffer Your Go-To Mutable Sequence 355 12.8 Deleting Array and ArrayBuffer Elements 357 12.9 Creating and Updating an Array 359 12.10 Creating Multidimensional Arrays 362 12.11 Sorting Arrays 365 13. Collections: Common Sequence Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 13.1 Choosing a Collection Method to Solve a Problem 371 13.2 Looping Over a Collection with foreach 378 13.3 Using Iterators 381 13.4 Using zipWithIndex or zip to Create Loop Counters 385 13.5 Transforming One Collection to Another with map 387 13.6 Flattening a List of Lists with flatten 390 13.7 Using filter to Filter a Collection 392 13.8 Extracting a Sequence of Elements from a Collection 395 13.9 Splitting Sequences into Subsets 397 13.10 Walking Through a Collection with the reduce and fold Methods 400 13.11 Finding the Unique Elements in a Sequence 405 13.12 Merging Sequential Collections 406 13.13 Randomizing a Sequence 409 13.14 Sorting a Collection 410 13.15 Converting a Collection to a String with mkString and addString 415 14. Collections: Using Maps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 14.1 Creating and Using Maps 419 14.2 Choosing a Map Implementation 422 14.3 Adding, Updating, and Removing Immutable Map Elements 425 14.4 Adding, Updating, and Removing Elements in Mutable Maps 427 14.5 Accessing Map Values (Without Exceptions) 429 14.6 Testing for the Existence of a Key or Value in a Map 431 14.7 Getting the Keys or Values from a Map 432 14.8 Finding the Largest (or Smallest) Key or Value in a Map 433 14.9 Traversing a Map 435 14.10 Sorting an Existing Map by Key or Value 438 14.11 Filtering a Map 441 Table of Contents | ix
📄 Page 12
15. Collections: Tuple, Range, Set, Stack, and Queue. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 15.1 Creating Heterogeneous Lists with Tuples 446 15.2 Creating Ranges 449 15.3 Creating a Set and Adding Elements to It 453 15.4 Deleting Elements from Sets 455 15.5 Storing Values in a Set in Sorted Order 457 15.6 Creating and Using a Stack 458 15.7 Creating and Using a Queue 460 16. Files and Processes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 16.1 Reading Text Files 464 16.2 Writing Text Files 468 16.3 Reading and Writing Binary Files 470 16.4 Pretending That a String Is a File 472 16.5 Serializing and Deserializing Objects to Files 473 16.6 Listing Files in a Directory 475 16.7 Executing External Commands 477 16.8 Executing External Commands and Reading Their STDOUT 480 16.9 Handling Both STDOUT and STDERR of Commands 483 16.10 Building a Pipeline of External Commands 485 17. Building Projects with sbt. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 17.1 Creating a Project Directory Structure for sbt 490 17.2 Building Projects with the sbt Command 495 17.3 Understanding build.sbt Syntax Styles 497 17.4 Compiling, Running, and Packaging a Scala Project 499 17.5 Understanding Other sbt Commands 501 17.6 Continuous Compiling and Testing 504 17.7 Managing Dependencies with sbt 505 17.8 Controlling Which Version of a Managed Dependency Is Used 510 17.9 Generating Project API Documentation 512 17.10 Specifying a Main Class to Run with sbt 513 17.11 Deploying a Single Executable JAR File 515 17.12 Publishing Your Library 517 18. Concurrency with Scala Futures and Akka Actors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521 18.1 Creating a Future 525 18.2 Using Callback and Transformation Methods with Futures 528 18.3 Writing Methods That Return Futures 532 x | Table of Contents
📄 Page 13
18.4 Running Multiple Futures in Parallel 534 18.5 Creating OOP-Style Actors 538 18.6 Creating FP-Style Actors 543 18.7 Sending Messages to Actors 546 18.8 Creating Actors That Have Multiple States (FSM) 552 19. Play Framework and Web Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 19.1 Creating a Play Framework Project 558 19.2 Creating a New Play Framework Endpoint 564 19.3 Returning JSON from a GET Request with Play 568 19.4 Serializing a Scala Object to a JSON String 572 19.5 Deserializing JSON into a Scala Object 576 19.6 Using the Play JSON Library Outside of the Play Framework 581 19.7 Using the sttp HTTP Client 584 20. Apache Spark. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 20.1 Getting Started with Spark 591 20.2 Reading a File into a Spark RDD 595 20.3 Reading a CSV File into a Spark RDD 600 20.4 Using Spark Like a Database with DataFrames 602 20.5 Reading Data Files into a Spark DataFrame 608 20.6 Using Spark SQL Queries Against Multiple Files 612 20.7 Creating a Spark Batch Application 616 21. Scala.js, GraalVM, and jpackage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619 21.1 Getting Started with Scala.js 620 21.2 Responding to Events with Scala.js 625 21.3 Building Single-Page Applications with Scala.js 632 21.4 Building Native Executables with GraalVM 638 21.5 Bundling Your Application with jpackage 641 22. Integrating Scala with Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 22.1 Using Java Collections in Scala 648 22.2 Using Scala Collections in Java 652 22.3 Using Java Optional Values in Scala 654 22.4 Using Scala Option Values in Java 656 22.5 Using Scala Traits in Java 659 22.6 Using Java Interfaces in Scala 660 22.7 Adding Exception Annotations to Scala Methods 661 Table of Contents | xi
📄 Page 14
22.8 Annotating varargs Methods to Work with Java 662 22.9 Using @SerialVersionUID and Other Annotations 664 23. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 23.1 Creating a Method That Takes a Simple Generic Type 677 23.2 Creating Classes That Use Simple Generic Types 678 23.3 Making Immutable Generic Parameters Covariant 682 23.4 Creating a Class Whose Generic Elements Can Be Mutated 684 23.5 Creating a Class Whose Parameters Implement a Base Type 687 23.6 Using Duck Typing (Structural Types) 689 23.7 Creating Meaningful Type Names with Opaque Types 691 23.8 Using Term Inference with given and using 695 23.9 Simulating Dynamic Typing with Union Types 701 23.10 Declaring That a Value Is a Combination of Types 703 23.11 Controlling How Classes Can Be Compared with Multiversal Equality 706 23.12 Limiting Equality Comparisons with the CanEqual Typeclass 707 24. Best Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 24.1 Writing Pure Functions 713 24.2 Using Immutable Variables and Collections 719 24.3 Writing Expressions (Instead of Statements) 722 24.4 Using Match Expressions and Pattern Matching 725 24.5 Eliminating null Values from Your Code 728 24.6 Using Scala’s Error-Handling Types (Option, Try, and Either) 733 24.7 Building Modular Systems 740 24.8 Handling Option Values with Higher-Order Functions 744 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749 xii | Table of Contents
📄 Page 15
Preface This is a cookbook of problem-solving recipes about Scala 3, the most interesting programming language I’ve ever used. The book contains solutions to more than two hundred fifty common Scala programming problems, demonstrated with more than one thousand examples. Compared to other Scala 3 learning resources, there are several unique things about this book: • As a cookbook, it’s intended to save you time by providing solutions to the most common problems you’ll encounter. • The book covers not only the Scala language but also recipes on Scala tools and libraries, including sbt, Spark, Scala.js, Akka actors, and JSON processing with the Play Framework. • The book takes a big dive into the Scala collections classes, using five chapters to demonstrate their use. • Output from the examples is shown either in the Scala interpreter or in com‐ ments after the code. As a result, whether you’re sitting by a computer, on a plane, or reading in your favorite recliner, you get the benefit of seeing their exact output. (Which often leads to, “Ah, so that’s how that works.”) The Scala 3 Language In the first edition of Scala Cookbook, I described Scala 2 as feeling like a combination of Ruby and Java. Back then I wrote, “My (oversimplified) Scala elevator pitch is that it’s a child of Ruby and Java: it’s light, concise, and readable like Ruby, but it compiles to class files that you package as JAR files that run on the Java virtual machine (JVM); it uses traits and mixins, and feels dynamic, but it’s statically typed.” xiii
📄 Page 16
Since then, the Scala language features have been rethought and debated in an open, public process, and with the release of Scala 3 in 2021, the language feels even lighter, and now it seems like a combination of four terrific languages: Ruby and Java, com‐ bined with the lightweight and clean syntax of Python and Haskell. Part of this even-lighter feel is thanks to the new optional braces syntax, which is also known as a significant indentation style. With this one change, for loops that used to look like this: for (i <- 1 to 5) { println(i) } now look like this: for i <- 1 to 5 do println(i) Similarly, if expressions and many other expressions also use less boilerplate syntax and are easier to read: val y = if (x == 1) { true } else { false } // Scala 2 val y = if x == 1 then true else false // Scala 3 While this new syntax is considered optional, it’s become the de facto standard and is used in this book, the Scala 3 Book that I cowrote for the Scala documentation web‐ site, the official Scala 3 training classes on Coursera, the books Programming in Scala by Martin Odersky et al. (Artima Press) and Programming Scala by Dean Wampler (O’Reilly), and many more learning resources. The new syntax isn’t the only change. Scala 3 has many new features, including: • Enumerations • Union and intersection types • Top-level definitions (so your code no longer has to be contained inside classes, traits, and objects) • Simplified use of implicits with the new given and using syntax • Greatly simplified syntax for extension methods and type classes Even the syntax of traits and classes has been simplified to be more readable than ever before: trait Animal: def speak(): Unit trait HasTail: def wagTail(): Unit class Dog extends Animal, HasTail: def speak() = println("Woof") def wagTail() = println("⎞⎜⎛ ⎞⎜⎛") xiv | Preface
📄 Page 17
With the new syntax, every construct that creates unnecessary “noise” in your code has been removed. Scala Features In addition to everything just stated, Scala provides a multitude of features that make it a unique and truly modern programming language: • It’s created by Martin Odersky—the “father” of javac—and influenced by Java, Ruby, Smalltalk, ML, Haskell, Python, Erlang, and others. • It’s a high-level programming language. • It has a concise, readable syntax—we call it expressive. • It’s statically typed—so you get to enjoy all the benefits of static type safety—but it feels like a dynamic scripting language. • It’s a pure object-oriented programming (OOP) language; every variable is an object, and every operator is a method. • It’s also a functional programming (FP) language, so you can pass functions around as variables. • Indeed, the essence of Scala is, as Mr. Odersky puts it, that it’s a fusion of FP and OOP in a typed setting, with: — Functions for the logic — Objects for the modularity • It runs on the JVM, and thanks to the Scala.js project, it’s also a type-safe Java‐ Script replacement. • It interacts seamlessly with Java and other JVM libraries. • Thanks to GraalVM and Scala Native, you can now create fast-starting native executables from your Scala code. • The innovative Scala collections library has dozens of prebuilt functional meth‐ ods to save you time and greatly reduces the need to write custom for loops and algorithms. • Programming best practices are built into Scala, which favors immutability, anonymous functions, higher-order functions, pattern matching, classes that cannot be extended by default, and much more. • The Scala ecosystem offers the most modern FP libraries in the world. One thing that I love about Scala is that if you’re familiar with Java, you can be pro‐ ductive with Scala on day 1—but the language is deep, so as you go along you’ll keep learning and finding newer, better ways to write code. Scala will change the way you think about programming—and that’s a good thing. Preface | xv
📄 Page 18
Of all of Scala’s benefits, what I like best is that it lets you write concise, readable code. The time a programmer spends reading code compared to the time spent writing code is said to be at least a 10:1 ratio, so writing code that’s concise and readable is a big deal. Scala Feels Light and Dynamic More than just being expressive, Scala feels like a light, dynamic scripting language. For instance, Scala’s type inference system eliminates the need for the obvious. Rather than always having to specify types, you simply assign your variables to their data: val hello = "Hello, world" // a String val i = 1 // an Int val x = 1.0 // a Double Notice that there’s no need to declare that a variable is a String, Int, or Double. This is Scala’s type inference system at work. Creating your own custom types works in exactly the same way. Given a Person class: class Person(val name: String) you can create a single person: val p = Person("Martin Odersky") or multiple people in a list, with no unnecessary boilerplate code: val scalaCenterFolks = List( Person("Darja Jovanovic"), Person("Julien Richard-Foy"), Person("Sébastien Doeraene") ) And even though I haven’t introduced for expressions yet, I suspect that any devel‐ oper with a little bit of experience can understand this code: for person <- scalaCenterFolks if person.name.startsWith("D") do println(person.name) And even though I haven’t introduced enums yet, the same developer likely knows what this code means: enum Topping: case Cheese, Pepperoni, Mushrooms, Olives Notice again that there’s no unnecessary boilerplate code here; the code is as “mini‐ malist” as possible, but still easily readable. Great care has been taken to continue Sca‐ la’s tradition of being an expressive language. xvi | Preface
📄 Page 19
In all of these examples you can see Scala’s lightweight syntax, and how it feels like a dynamic scripting language. Audience This book is intended for programmers who want to be able to quickly find solutions to problems they’ll encounter when using Scala and its libraries and tools. I hope it will also be a good tool for developers who want to learn Scala. I’m a big believer in learning by example, and this book is chock-full of examples. I generally assume that you have some experience with another programming lan‐ guage like C, C++, Java, Ruby, C#, PHP, Python, Haskell, and the like. My own experi‐ ence is with those languages, so I’m sure my writing is influenced by that background. Another way to describe the audience for this book involves looking at different levels of software developers. In this article on Scala levels, Martin Odersky defines the fol‐ lowing levels of computer programmers: • Level A1: Beginning application programmer • Level A2: Intermediate application programmer • Level A3: Expert application programmer • Level L1: Junior library designer • Level L2: Senior library designer • Level L3: Expert library designer This book is primarily aimed at the application developers in the A1, A2, A3, and L1 categories. While helping those developers is my primary goal, I hope that L2 and L3 developers can also benefit from the many examples in this book―especially if they have no prior experience with functional programming, or they want to quickly get up to speed with Scala and its tools and libraries. Contents of This Book This book is all about solutions, and Chapter 1, Command-Line Tasks contains a col‐ lection of recipes centered around using Scala at the command line. It begins by showing tips on how to use the Scala REPL, as well as the feature-packed Ammonite REPL. It then shows how to use command-line tools like scalac and scala to com‐ pile and run your code, as well as the javap command to disassemble your Scala class files. Finally, it shows how to run Scala-generated JAR files. Preface | xvii
📄 Page 20
Chapter 2, Strings provides recipes for working with strings. Scala gets its basic String functionality from Java, but with the power of implicit conversions, Scala adds new functionality to strings, so you can also treat them as a sequence of charac‐ ters (Char values). Chapter 3, Numbers and Dates provides recipes for working with Scala’s numeric types, as well as the date classes that were introduced with Java 8. In the numeric rec‐ ipes, you’ll see that there are no ++ and –– operators for working with numbers; this chapter explains why and demonstrates the other methods you can use. It also shows how to handle large numbers, currency, and how to compare floating-point numbers. The date recipes use the Java 8 date classes and also show how to work with legacy dates. Chapter 4, Control Structures demonstrates Scala’s built-in control structures, starting with if/then statements and basic for loops, and then provides solutions for working with for/yield loops (for comprehensions), and for expressions with embedded if statements (guards). Because match expressions and pattern matching are so impor‐ tant to Scala, several recipes show how to use them to solve a variety of problems. Chapter 5, Classes provides examples related to Scala classes, parameters, and fields. Because Scala constructors are very different than Java constructors, several recipes show the ins and outs of writing both primary and auxiliary constructors. Several rec‐ ipes show what case classes are and how to use them. Chapter 6, Traits and Enums provides examples of the all-important Scala trait, as well as the brand-new enum. The trait recipes begin by showing how to use a trait like a Java interface, and then they dive into more advanced topics, such as how to use traits as mixins, and how to limit which members a trait can be mixed into using a variety of methods. The final two recipes demonstrate how to use enums in domain modeling, including the creation of algebraic data types (ADTs). Chapter 7, Objects contains recipes related to objects, including the meaning of an object as an instance of a class, as well as everything related to the object keyword. Chapter 8, Methods shows how to define methods to accept parameters, return val‐ ues, use parameter names when calling methods, set default values for method parameters, create varargs fields, and write methods to support a fluent style of pro‐ gramming. The last recipe in the chapter demonstrates the all-new Scala 3 extension methods. Chapter 9, Packaging and Imports contains examples of Scala’s package and import statements, which provide more capabilities than the same Java keywords. This includes how to use the curly brace style for packaging, how to hide and rename members when you import them, and more. xviii | Preface
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List