Learning Scala Author Jason Swartz demonstrates why Scala’s concise and expressive syntax make it an ideal language for Ruby or Python developers who want to improve their craft, while its type safety and performance ensures that it’s stable and fast enough for any application ■■ Learn about the core data types, literals, values, and variables ■■ Discover how to think and write in expressions, the foundation for Scala's syntax ■■ Write higher-order functions that accept or return other functions ■■ Become familiar with immutable data structures and easily transform them with type-safe and declarative operations ■■ Create custom infix operators to simplify existing operations or even to start your own domain-specific language ■■ Build classes that compose one or more traits for full reusability, or create new functionality by mixing them in at instantiation you're “ Whether experienced in Python or more familiar with Java, you'll find this book a friendly introduction to Scala Jason's writing is practical and approachable; Learning Scala provides a clear beginner's guide by combining a familiar object-oriented style with idiomatic features of the language It's the book I wish I had when I first started! ” Learning Scala Why learn Scala? You don’t need to be a data scientist or distributed computing expert to appreciate this object-oriented functional programming language This practical book provides a comprehensive yet approachable introduction to the language, complete with syntax diagrams, examples, and exercises You’ll start with Scala's core types and syntax before diving into higher-order functions and immutable data structures Learning Scala PRACTICAL FUNCTIONAL PROGRAMMING FOR THE JVM —Katherine Fellows Software Engineer, Comcast, Inc Jason Swartz is a software developer who adores intuitive user interfaces, expressive programming languages, and concise user documentation He also organizes Scala community events in San Francisco and develops applications for Netflix’s consumer device program US $39.99 Twitter: @oreillymedia facebook.com/oreilly Swartz SC AL A /JAVA /PROGR AMMING L ANGUAGES CAN $41.99 ISBN: 978-1-449-36793-0 Jason Swartz Learning Scala Author Jason Swartz demonstrates why Scala’s concise and expressive syntax make it an ideal language for Ruby or Python developers who want to improve their craft, while its type safety and performance ensures that it’s stable and fast enough for any application ■■ Learn about the core data types, literals, values, and variables ■■ Discover how to think and write in expressions, the foundation for Scala's syntax ■■ Write higher-order functions that accept or return other functions ■■ Become familiar with immutable data structures and easily transform them with type-safe and declarative operations ■■ Create custom infix operators to simplify existing operations or even to start your own domain-specific language ■■ Build classes that compose one or more traits for full reusability, or create new functionality by mixing them in at instantiation you're “ Whether experienced in Python or more familiar with Java, you'll find this book a friendly introduction to Scala Jason's writing is practical and approachable; Learning Scala provides a clear beginner's guide by combining a familiar object-oriented style with idiomatic features of the language It's the book I wish I had when I first started! ” Learning Scala Why learn Scala? You don’t need to be a data scientist or distributed computing expert to appreciate this object-oriented functional programming language This practical book provides a comprehensive yet approachable introduction to the language, complete with syntax diagrams, examples, and exercises You’ll start with Scala's core types and syntax before diving into higher-order functions and immutable data structures Learning Scala PRACTICAL FUNCTIONAL PROGRAMMING FOR THE JVM —Katherine Fellows Software Engineer, Comcast, Inc Jason Swartz is a software developer who adores intuitive user interfaces, expressive programming languages, and concise user documentation He also organizes Scala community events in San Francisco and develops applications for Netflix’s consumer device program US $39.99 Twitter: @oreillymedia facebook.com/oreilly Swartz SC AL A /JAVA /PROGR AMMING L ANGUAGES CAN $41.99 ISBN: 978-1-449-36793-0 Jason Swartz Learning Scala Jason Swartz Learning Scala by Jason Swartz Copyright © 2015 Jason Swartz 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://safaribooksonline.com) For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Simon St Laurent and Meghan Blanchette Production Editor: Colleen Lobner Copyeditor: Kim Cofer Proofreader: Charles Roumeliotis December 2014: Indexer: Ellen Troutman Cover Designer: Ellie Volckhausen Interior Designer: David Futato Illustrator: Rebecca Demarest First Edition Revision History for the First Edition: 2014-12-08: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449367930 for release details The O’Reilly logo is a registered trademark of O’Reilly Media, Inc Learning Scala, the cover image, 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 trademark claim, the designations have been printed in caps or initial caps While the publisher and the authors have used good faith efforts to ensure that the information and in‐ structions contained in this work are accurate, the publisher and the authors 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 ISBN: 978-1-449-36793-0 [LSI] For my loving wife, who foresees great prospects; and for my loving daughter, who also foresees the first printed copy coming her way Table of Contents Preface ix Part I Core Scala Getting Started with the Scalable Language Installing Scala Using the Scala REPL Summary Exercises 6 Working with Data: Literals, Values, Variables, and Types Values Variables Naming Types Numeric Data Types Strings An Overview of Scala Types Tuples Summary Exercises 10 12 13 15 15 17 21 25 26 26 Expressions and Conditionals 27 Expressions Defining Values and Variables with Expressions Expression Blocks Statements If Else Expression Blocks If Expressions 27 28 28 29 30 30 v If-Else Expressions Match Expressions Matching with Wildcard Patterns Matching with Pattern Guards Matching Types with Pattern Variables Loops Iterator Guards Nested Iterators Value Binding While and Do/While Loops Summary Exercises 31 31 34 36 36 37 39 39 40 40 41 42 Functions 45 Procedures Functions with Empty Parentheses Function Invocation with Expression Blocks Recursive Functions Nested Functions Calling Functions with Named Parameters Parameters with Default Values Vararg Parameters Parameter Groups Type Parameters Methods and Operators Writing Readable Functions Summary Exercises 48 48 49 50 52 53 53 54 55 55 57 60 62 62 First-Class Functions 65 Function Types and Values Higher-Order Functions Function Literals Placeholder Syntax Partially Applied Functions and Currying By-Name Parameters Partial Functions Invoking Higher-Order Functions with Function Literal Blocks Summary Exercises vi | Table of Contents 66 68 69 72 74 75 76 78 80 81 Common Collections 83 Lists, Sets, and Maps What’s in a List? The Cons Operator List Arithmetic Mapping Lists Reducing Lists Converting Collections Java and Scala Collection Compatibility Pattern Matching with Collections Summary Exercises 83 86 89 90 92 93 98 99 100 101 102 More Collections 107 Mutable Collections Creating New Mutable Collections Creating Mutable Collections from Immutable Ones Using Collection Builders Arrays Seq and Sequences Streams Monadic Collections Option Collections Try Collections Future Collections Summary Exercises Part II 107 108 109 111 112 113 115 117 117 121 125 130 131 Object-Oriented Scala Classes 137 Defining Classes More Class Types Abstract Classes Anonymous Classes More Field and Method Types Overloaded Methods Apply Methods Lazy Values Packaging Accessing Packaged Classes 142 146 146 148 149 149 150 150 151 152 Table of Contents | vii Packaging Syntax Privacy Controls Privacy Access Modifiers Final and Sealed Classes Summary Exercises 156 158 160 161 162 162 Objects, Case Classes, and Traits 167 Objects Apply Methods and Companion Objects Command-Line Applications with Objects Case Classes Traits Self Types Instantiation with Traits Importing Instance Members Summary Break—Configuring Your First Scala Project Exercises 167 169 172 173 176 180 182 184 185 186 191 10 Advanced Typing 199 Tuple and Function Value Classes Implicit Parameters Implicit Classes Types Type Aliases Abstract Types Bounded Types Type Variance Package Objects Summary Questions 201 203 205 207 207 208 209 212 216 217 218 A Reserved Words 221 Index 225 viii | Table of Contents Name Description var Defines a new, mutable variable while Part of the while loop definition with Defines a base trait for a class yield Yields the return value from a for-loop Where Are My Favorite :: and ++ Operators? The :: and ++ operators are valid method identifiers, not reserved words The Scala collections library defines methods with these iden‐ tifiers, which means you can also use them for your own methods Reserved Words | 223 Index Symbols " (quotation marks, double) enclosing string literals, 17 “"” (triple quotes), for multiline strings, 18 $ (dollar sign) referencing external data in string interpola‐ tion, 18 & (ampersand) & (Boolean and) operator, 23 && versus & operator, 23 ' (quotation marks, single) enclosing Char literals, 23 ( ) (parentheses) defining capture group in regular expres‐ sions, 20 denoting a Unit literal, 24 enclosing Boolean expression in if expres‐ sion, 36 enclosing tuples, 25 grouping function parameters, 55 in for-loops, 38 in functions, 48, 50 leaving out for single-parameter func‐ tions, 67 * (asterisk) in vararg parameters, 54 multiplication operator, 13 -> relation operator, 86 (period), member access operator, 13 dot notation, 57, 91 accessing class fields and methods, 143 / (slash) division operator, 118 : (colon) :: (cons) operator, 89