Top Banner
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
754

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index · 2017. 6. 8. · Overview Contents vii List of Figures xvii List of Tables xix List of Listings xx Foreword

Aug 19, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=i

  • Programming in Scala

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=ii

  • Programming in ScalaMartin Odersky, Lex Spoon, Bill Venners

    artimaARTIMA PRESS

    MOUNTAIN VIEW, CALIFORNIA

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=iii

  • iv

    Programming in ScalaFirst Edition, Version 6

    Martin Odersky is the creator of the Scala language and a professor at EPFL inLausanne, Switzerland. Lex Spoon worked on Scala for two years as a post-docwith Martin Odersky. Bill Venners is president of Artima, Inc.

    Artima Press is an imprint of Artima, Inc.P.O. Box 390122, Mountain View, California 94039

    Copyright © 2007, 2008 Martin Odersky, Lex Spoon, and Bill Venners.All rights reserved.

    First edition published as PrePrint™ eBook 2007First edition published 2008Produced in the United States of America

    12 11 10 09 08 5 6 7 8 9

    ISBN-10: 0-9815316-1-XISBN-13: 978-0-9815316-1-8

    No part of this publication may be reproduced, modified, distributed, stored in aretrieval system, republished, displayed, or performed, for commercial ornoncommercial purposes or for compensation of any kind without prior writtenpermission from Artima, Inc.

    All information and materials in this book are provided "as is" and withoutwarranty of any kind.

    The term “Artima” and the Artima logo are trademarks or registered trademarks ofArtima, Inc. All other company and/or product names may be trademarks orregistered trademarks of their owners.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=iv

  • to Nastaran - M.O.

    to Fay - L.S.

    to Siew - B.V.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=v

  • OverviewContents viiList of Figures xviiList of Tables xixList of Listings xxForeword xxviiAcknowledgments xxixIntroduction xxxi1. A Scalable Language 392. First Steps in Scala 583. Next Steps in Scala 714. Classes and Objects 935. Basic Types and Operations 1076. Functional Objects 1297. Built-in Control Structures 1498. Functions and Closures 1739. Control Abstraction 19410. Composition and Inheritance 20911. Scala’s Hierarchy 23712. Traits 24513. Packages and Imports 26414. Assertions and Unit Testing 27915. Case Classes and Pattern Matching 29316. Working with Lists 32717. Collections 35918. Stateful Objects 38719. Type Parameterization 41020. Abstract Members 43521. Implicit Conversions and Parameters 46522. Implementing Lists 48723. For Expressions Revisited 50024. Extractors 51625. Annotations 53226. Working with XML 53927. Modular Programming Using Objects 55328. Object Equality 56829. Combining Scala and Java 59430. Actors and Concurrency 60731. Combinator Parsing 64232. GUI Programming 67133. The SCells Spreadsheet 683A. Scala scripts on Unix and Windows 708Glossary 709Bibliography 725About the Authors 728Index 729

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=vi

  • Contents

    Contents vii

    List of Figures xvii

    List of Tables xix

    List of Listings xx

    Foreword xxvii

    Acknowledgments xxix

    Introduction xxxi

    1 A Scalable Language 391.1 A language that grows on you . . . . . . . . . . . . . . 401.2 What makes Scala scalable? . . . . . . . . . . . . . . . 451.3 Why Scala? . . . . . . . . . . . . . . . . . . . . . . . . 481.4 Scala’s roots . . . . . . . . . . . . . . . . . . . . . . . 551.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 57

    2 First Steps in Scala 58Step 1. Learn to use the Scala interpreter . . . . . . . . . . . . 58Step 2. Define some variables . . . . . . . . . . . . . . . . . 60Step 3. Define some functions . . . . . . . . . . . . . . . . . 62Step 4. Write some Scala scripts . . . . . . . . . . . . . . . . 64Step 5. Loop with while; decide with if . . . . . . . . . . . 65Step 6. Iterate with foreach and for . . . . . . . . . . . . . 67Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=vii

  • Contents viii

    3 Next Steps in Scala 71Step 7. Parameterize arrays with types . . . . . . . . . . . . 71Step 8. Use lists . . . . . . . . . . . . . . . . . . . . . . . . 75Step 9. Use tuples . . . . . . . . . . . . . . . . . . . . . . . 80Step 10. Use sets and maps . . . . . . . . . . . . . . . . . . . 81Step 11. Learn to recognize the functional style . . . . . . . . 86Step 12. Read lines from a file . . . . . . . . . . . . . . . . . 89Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

    4 Classes and Objects 934.1 Classes, fields, and methods . . . . . . . . . . . . . . . 934.2 Semicolon inference . . . . . . . . . . . . . . . . . . . 984.3 Singleton objects . . . . . . . . . . . . . . . . . . . . . 994.4 A Scala application . . . . . . . . . . . . . . . . . . . 1024.5 The Application trait . . . . . . . . . . . . . . . . . . 1054.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 106

    5 Basic Types and Operations 1075.1 Some basic types . . . . . . . . . . . . . . . . . . . . . 1075.2 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . 1085.3 Operators are methods . . . . . . . . . . . . . . . . . . 1155.4 Arithmetic operations . . . . . . . . . . . . . . . . . . 1185.5 Relational and logical operations . . . . . . . . . . . . 1195.6 Bitwise operations . . . . . . . . . . . . . . . . . . . . 1215.7 Object equality . . . . . . . . . . . . . . . . . . . . . . 1235.8 Operator precedence and associativity . . . . . . . . . . 1245.9 Rich wrappers . . . . . . . . . . . . . . . . . . . . . . 1275.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 127

    6 Functional Objects 1296.1 A specification for class Rational . . . . . . . . . . . 1296.2 Constructing a Rational . . . . . . . . . . . . . . . . 1306.3 Reimplementing the toString method . . . . . . . . . 1326.4 Checking preconditions . . . . . . . . . . . . . . . . . 1336.5 Adding fields . . . . . . . . . . . . . . . . . . . . . . . 1336.6 Self references . . . . . . . . . . . . . . . . . . . . . . 1356.7 Auxiliary constructors . . . . . . . . . . . . . . . . . . 1366.8 Private fields and methods . . . . . . . . . . . . . . . . 138

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=viii

  • Contents ix

    6.9 Defining operators . . . . . . . . . . . . . . . . . . . . 1396.10 Identifiers in Scala . . . . . . . . . . . . . . . . . . . . 1416.11 Method overloading . . . . . . . . . . . . . . . . . . . 1446.12 Implicit conversions . . . . . . . . . . . . . . . . . . . 1466.13 A word of caution . . . . . . . . . . . . . . . . . . . . 1476.14 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 147

    7 Built-in Control Structures 1497.1 If expressions . . . . . . . . . . . . . . . . . . . . . . 1507.2 While loops . . . . . . . . . . . . . . . . . . . . . . . 1517.3 For expressions . . . . . . . . . . . . . . . . . . . . . . 1547.4 Exception handling with try expressions . . . . . . . . 1597.5 Match expressions . . . . . . . . . . . . . . . . . . . . 1637.6 Living without break and continue . . . . . . . . . . 1657.7 Variable scope . . . . . . . . . . . . . . . . . . . . . . 1677.8 Refactoring imperative-style code . . . . . . . . . . . . 1707.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 172

    8 Functions and Closures 1738.1 Methods . . . . . . . . . . . . . . . . . . . . . . . . . 1738.2 Local functions . . . . . . . . . . . . . . . . . . . . . . 1758.3 First-class functions . . . . . . . . . . . . . . . . . . . 1778.4 Short forms of function literals . . . . . . . . . . . . . 1798.5 Placeholder syntax . . . . . . . . . . . . . . . . . . . . 1808.6 Partially applied functions . . . . . . . . . . . . . . . . 1818.7 Closures . . . . . . . . . . . . . . . . . . . . . . . . . 1848.8 Repeated parameters . . . . . . . . . . . . . . . . . . . 1888.9 Tail recursion . . . . . . . . . . . . . . . . . . . . . . . 1898.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 193

    9 Control Abstraction 1949.1 Reducing code duplication . . . . . . . . . . . . . . . . 1949.2 Simplifying client code . . . . . . . . . . . . . . . . . 1989.3 Currying . . . . . . . . . . . . . . . . . . . . . . . . . 2009.4 Writing new control structures . . . . . . . . . . . . . . 2029.5 By-name parameters . . . . . . . . . . . . . . . . . . . 2059.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 208

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=ix

  • Contents x

    10 Composition and Inheritance 20910.1 A two-dimensional layout library . . . . . . . . . . . . 20910.2 Abstract classes . . . . . . . . . . . . . . . . . . . . . 21010.3 Defining parameterless methods . . . . . . . . . . . . . 21110.4 Extending classes . . . . . . . . . . . . . . . . . . . . 21410.5 Overriding methods and fields . . . . . . . . . . . . . . 21610.6 Defining parametric fields . . . . . . . . . . . . . . . . 21710.7 Invoking superclass constructors . . . . . . . . . . . . . 21910.8 Using override modifiers . . . . . . . . . . . . . . . . 22010.9 Polymorphism and dynamic binding . . . . . . . . . . 22210.10 Declaring final members . . . . . . . . . . . . . . . . . 22410.11 Using composition and inheritance . . . . . . . . . . . 22610.12 Implementing above, beside, and toString . . . . . . 22710.13 Defining a factory object . . . . . . . . . . . . . . . . . 22910.14 Heighten and widen . . . . . . . . . . . . . . . . . . . 23110.15 Putting it all together . . . . . . . . . . . . . . . . . . . 23510.16 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 236

    11 Scala’s Hierarchy 23711.1 Scala’s class hierarchy . . . . . . . . . . . . . . . . . . 23711.2 How primitives are implemented . . . . . . . . . . . . 24111.3 Bottom types . . . . . . . . . . . . . . . . . . . . . . . 24311.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 244

    12 Traits 24512.1 How traits work . . . . . . . . . . . . . . . . . . . . . 24512.2 Thin versus rich interfaces . . . . . . . . . . . . . . . . 24812.3 Example: Rectangular objects . . . . . . . . . . . . . . 24912.4 The Ordered trait . . . . . . . . . . . . . . . . . . . . 25212.5 Traits as stackable modifications . . . . . . . . . . . . . 25412.6 Why not multiple inheritance? . . . . . . . . . . . . . . 25812.7 To trait, or not to trait? . . . . . . . . . . . . . . . . . . 26212.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 263

    13 Packages and Imports 26413.1 Packages . . . . . . . . . . . . . . . . . . . . . . . . . 26413.2 Imports . . . . . . . . . . . . . . . . . . . . . . . . . . 26813.3 Implicit imports . . . . . . . . . . . . . . . . . . . . . 272

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=x

  • Contents xi

    13.4 Access modifiers . . . . . . . . . . . . . . . . . . . . . 27313.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 278

    14 Assertions and Unit Testing 27914.1 Assertions . . . . . . . . . . . . . . . . . . . . . . . . 27914.2 Unit testing in Scala . . . . . . . . . . . . . . . . . . . 28114.3 Informative failure reports . . . . . . . . . . . . . . . . 28214.4 Using JUnit and TestNG . . . . . . . . . . . . . . . . . 28414.5 Tests as specifications . . . . . . . . . . . . . . . . . . 28614.6 Property-based testing . . . . . . . . . . . . . . . . . . 28814.7 Organizing and running tests . . . . . . . . . . . . . . 29014.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 292

    15 Case Classes and Pattern Matching 29315.1 A simple example . . . . . . . . . . . . . . . . . . . . 29315.2 Kinds of patterns . . . . . . . . . . . . . . . . . . . . . 29815.3 Pattern guards . . . . . . . . . . . . . . . . . . . . . . 30715.4 Pattern overlaps . . . . . . . . . . . . . . . . . . . . . 30915.5 Sealed classes . . . . . . . . . . . . . . . . . . . . . . 31015.6 The Option type . . . . . . . . . . . . . . . . . . . . . 31215.7 Patterns everywhere . . . . . . . . . . . . . . . . . . . 31415.8 A larger example . . . . . . . . . . . . . . . . . . . . . 31815.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 326

    16 Working with Lists 32716.1 List literals . . . . . . . . . . . . . . . . . . . . . . . . 32716.2 The List type . . . . . . . . . . . . . . . . . . . . . . 32816.3 Constructing lists . . . . . . . . . . . . . . . . . . . . . 32816.4 Basic operations on lists . . . . . . . . . . . . . . . . . 32916.5 List patterns . . . . . . . . . . . . . . . . . . . . . . . 33016.6 First-order methods on class List . . . . . . . . . . . . 33216.7 Higher-order methods on class List . . . . . . . . . . 34316.8 Methods of the List object . . . . . . . . . . . . . . . 35116.9 Understanding Scala’s type inference algorithm . . . . . 35516.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 358

    17 Collections 35917.1 Overview of the library . . . . . . . . . . . . . . . . . 359

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xi

  • Contents xii

    17.2 Sequences . . . . . . . . . . . . . . . . . . . . . . . . 36117.3 Sets and maps . . . . . . . . . . . . . . . . . . . . . . 36717.4 Selecting mutable versus immutable collections . . . . 37717.5 Initializing collections . . . . . . . . . . . . . . . . . . 38017.6 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . 38317.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 386

    18 Stateful Objects 38718.1 What makes an object stateful? . . . . . . . . . . . . . 38718.2 Reassignable variables and properties . . . . . . . . . . 39018.3 Case study: Discrete event simulation . . . . . . . . . . 39318.4 A language for digital circuits . . . . . . . . . . . . . . 39418.5 The Simulation API . . . . . . . . . . . . . . . . . . 39718.6 Circuit Simulation . . . . . . . . . . . . . . . . . . . . 40118.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 409

    19 Type Parameterization 41019.1 Functional queues . . . . . . . . . . . . . . . . . . . . 41019.2 Information hiding . . . . . . . . . . . . . . . . . . . . 41419.3 Variance annotations . . . . . . . . . . . . . . . . . . . 41719.4 Checking variance annotations . . . . . . . . . . . . . . 42119.5 Lower bounds . . . . . . . . . . . . . . . . . . . . . . 42419.6 Contravariance . . . . . . . . . . . . . . . . . . . . . . 42619.7 Object private data . . . . . . . . . . . . . . . . . . . . 42919.8 Upper bounds . . . . . . . . . . . . . . . . . . . . . . 43119.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 434

    20 Abstract Members 43520.1 A quick tour of abstract members . . . . . . . . . . . . 43520.2 Type members . . . . . . . . . . . . . . . . . . . . . . 43620.3 Abstract vals . . . . . . . . . . . . . . . . . . . . . . . 43720.4 Abstract vars . . . . . . . . . . . . . . . . . . . . . . . 43820.5 Initializing abstract vals . . . . . . . . . . . . . . . . . 43920.6 Abstract types . . . . . . . . . . . . . . . . . . . . . . 44720.7 Path-dependent types . . . . . . . . . . . . . . . . . . 44920.8 Enumerations . . . . . . . . . . . . . . . . . . . . . . . 45220.9 Case study: Currencies . . . . . . . . . . . . . . . . . . 45420.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 463

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xii

  • Contents xiii

    21 Implicit Conversions and Parameters 46521.1 Implicit conversions . . . . . . . . . . . . . . . . . . . 46521.2 Rules for implicits . . . . . . . . . . . . . . . . . . . . 46821.3 Implicit conversion to an expected type . . . . . . . . . 47121.4 Converting the receiver . . . . . . . . . . . . . . . . . 47321.5 Implicit parameters . . . . . . . . . . . . . . . . . . . . 47521.6 View bounds . . . . . . . . . . . . . . . . . . . . . . . 48121.7 Debugging implicits . . . . . . . . . . . . . . . . . . . 48521.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 486

    22 Implementing Lists 48722.1 The List class in principle . . . . . . . . . . . . . . . 48722.2 The ListBuffer class . . . . . . . . . . . . . . . . . . 49322.3 The List class in practice . . . . . . . . . . . . . . . . 49522.4 Functional on the outside . . . . . . . . . . . . . . . . 49722.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 498

    23 For Expressions Revisited 50023.1 For expressions . . . . . . . . . . . . . . . . . . . . . . 50123.2 The n-queens problem . . . . . . . . . . . . . . . . . . 50323.3 Querying with for expressions . . . . . . . . . . . . . 50623.4 Translation of for expressions . . . . . . . . . . . . . . 50823.5 Going the other way . . . . . . . . . . . . . . . . . . . 51223.6 Generalizing for . . . . . . . . . . . . . . . . . . . . . 51323.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 515

    24 Extractors 51624.1 An example: Extracting email addresses . . . . . . . . 51624.2 Extractors . . . . . . . . . . . . . . . . . . . . . . . . 51724.3 Patterns with zero or one variables . . . . . . . . . . . 52024.4 Variable argument extractors . . . . . . . . . . . . . . . 52224.5 Extractors and sequence patterns . . . . . . . . . . . . 52524.6 Extractors versus case classes . . . . . . . . . . . . . . 52624.7 Regular expressions . . . . . . . . . . . . . . . . . . . 52724.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 531

    25 Annotations 53225.1 Why have annotations? . . . . . . . . . . . . . . . . . 532

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xiii

  • Contents xiv

    25.2 Syntax of annotations . . . . . . . . . . . . . . . . . . 53325.3 Standard annotations . . . . . . . . . . . . . . . . . . . 53525.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 537

    26 Working with XML 53926.1 Semi-structured data . . . . . . . . . . . . . . . . . . . 53926.2 XML overview . . . . . . . . . . . . . . . . . . . . . . 54026.3 XML literals . . . . . . . . . . . . . . . . . . . . . . . 54126.4 Serialization . . . . . . . . . . . . . . . . . . . . . . . 54326.5 Taking XML apart . . . . . . . . . . . . . . . . . . . . 54526.6 Deserialization . . . . . . . . . . . . . . . . . . . . . . 54626.7 Loading and saving . . . . . . . . . . . . . . . . . . . 54726.8 Pattern matching on XML . . . . . . . . . . . . . . . . 54926.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 552

    27 Modular Programming Using Objects 55327.1 The problem . . . . . . . . . . . . . . . . . . . . . . . 55427.2 A recipe application . . . . . . . . . . . . . . . . . . . 55527.3 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . 55827.4 Splitting modules into traits . . . . . . . . . . . . . . . 56127.5 Runtime linking . . . . . . . . . . . . . . . . . . . . . 56427.6 Tracking module instances . . . . . . . . . . . . . . . . 56527.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 567

    28 Object Equality 56828.1 Equality in Scala . . . . . . . . . . . . . . . . . . . . . 56828.2 Writing an equality method . . . . . . . . . . . . . . . 56928.3 Defining equality for parameterized types . . . . . . . . 58228.4 Recipes for equals and hashCode . . . . . . . . . . . 58728.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 593

    29 Combining Scala and Java 59429.1 Using Scala from Java . . . . . . . . . . . . . . . . . . 59429.2 Annotations . . . . . . . . . . . . . . . . . . . . . . . 59729.3 Existential types . . . . . . . . . . . . . . . . . . . . . 60229.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 606

    30 Actors and Concurrency 607

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xiv

  • Contents xv

    30.1 Trouble in paradise . . . . . . . . . . . . . . . . . . . . 60730.2 Actors and message passing . . . . . . . . . . . . . . . 60830.3 Treating native threads as actors . . . . . . . . . . . . . 61230.4 Better performance through thread reuse . . . . . . . . 61330.5 Good actors style . . . . . . . . . . . . . . . . . . . . . 61630.6 A longer example: Parallel discrete event simulation . . 62330.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 640

    31 Combinator Parsing 64231.1 Example: Arithmetic expressions . . . . . . . . . . . . 64331.2 Running your parser . . . . . . . . . . . . . . . . . . . 64531.3 Basic regular expression parsers . . . . . . . . . . . . . 64631.4 Another example: JSON . . . . . . . . . . . . . . . . . 64731.5 Parser output . . . . . . . . . . . . . . . . . . . . . . . 64931.6 Implementing combinator parsers . . . . . . . . . . . . 65531.7 String literals and regular expressions . . . . . . . . . . 66431.8 Lexing and parsing . . . . . . . . . . . . . . . . . . . . 66531.9 Error reporting . . . . . . . . . . . . . . . . . . . . . . 66531.10 Backtracking versus LL(1) . . . . . . . . . . . . . . . . 66731.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 669

    32 GUI Programming 67132.1 A first Swing application . . . . . . . . . . . . . . . . . 67132.2 Panels and layouts . . . . . . . . . . . . . . . . . . . . 67432.3 Handling events . . . . . . . . . . . . . . . . . . . . . 67632.4 Example: Celsius/Fahrenheit converter . . . . . . . . . 67932.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 681

    33 The SCells Spreadsheet 68333.1 The visual framework . . . . . . . . . . . . . . . . . . 68333.2 Disconnecting data entry and display . . . . . . . . . . 68633.3 Formulas . . . . . . . . . . . . . . . . . . . . . . . . . 68933.4 Parsing formulas . . . . . . . . . . . . . . . . . . . . . 69133.5 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 69633.6 Operation libraries . . . . . . . . . . . . . . . . . . . . 69933.7 Change propagation . . . . . . . . . . . . . . . . . . . 70233.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 706

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xv

  • Contents xvi

    A Scala scripts on Unix and Windows 708

    Glossary 709

    Bibliography 725

    About the Authors 728

    Index 729

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xvi

  • List of Figures

    2.1 The basic form of a function definition in Scala. . . . . . . . 632.2 The syntax of a function literal in Scala. . . . . . . . . . . . 69

    3.1 All operations are method calls in Scala. . . . . . . . . . . . 743.2 Class hierarchy for Scala sets. . . . . . . . . . . . . . . . . 823.3 Class hierarchy for Scala maps. . . . . . . . . . . . . . . . . 84

    10.1 Class diagram for ArrayElement. . . . . . . . . . . . . . . 21510.2 Class diagram for LineElement. . . . . . . . . . . . . . . . 22010.3 Class hierarchy of layout elements . . . . . . . . . . . . . . 22310.4 Class hierarchy with revised LineElement. . . . . . . . . . 227

    11.1 Class hierarchy of Scala. . . . . . . . . . . . . . . . . . . . 239

    12.1 Inheritance hierarchy and linearization of class Cat. . . . . . 261

    14.1 ScalaTest’s graphical reporter. . . . . . . . . . . . . . . . . 291

    17.1 Class hierarchy for Scala collections. . . . . . . . . . . . . . 36017.2 Class hierarchy for Iterator. . . . . . . . . . . . . . . . . 361

    18.1 Basic gates. . . . . . . . . . . . . . . . . . . . . . . . . . . 39418.2 A half-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 39618.3 A full-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 397

    19.1 Covariance and contravariance in function type parameters. . 429

    22.1 Class hierarchy for Scala lists. . . . . . . . . . . . . . . . . 48822.2 The structure of the Scala lists shown in Listing 22.2. . . . . 492

    xvii

  • List of Figures xviii

    32.1 A simple Swing application: initial (left) and resized (right). 67232.2 A reactive Swing application: initial (left) after clicks (right). 67432.3 A converter between degrees Celsius and Fahrenheit. . . . . 679

    33.1 A simple spreadsheet table. . . . . . . . . . . . . . . . . . . 68433.2 Cells displaying themselves. . . . . . . . . . . . . . . . . . 68933.3 Cells displaying their formulas. . . . . . . . . . . . . . . . . 69533.4 Cells that evaluate. . . . . . . . . . . . . . . . . . . . . . . 701

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xviii

  • List of Tables

    3.1 Some List methods and usages . . . . . . . . . . . . . . . 78

    5.1 Some basic types . . . . . . . . . . . . . . . . . . . . . . . 1085.2 Special character literal escape sequences . . . . . . . . . . 1125.3 Operator precedence . . . . . . . . . . . . . . . . . . . . . 1265.4 Some rich operations . . . . . . . . . . . . . . . . . . . . . 1285.5 Rich wrapper classes . . . . . . . . . . . . . . . . . . . . . 128

    12.1 Linearization of types in Cat’s hierarchy . . . . . . . . . . . 262

    13.1 Effects of private qualifiers on LegOfJourney.distance . . 276

    16.1 Basic list operations . . . . . . . . . . . . . . . . . . . . . . 330

    17.1 Common operations for sets . . . . . . . . . . . . . . . . . 37017.2 Common operations for maps . . . . . . . . . . . . . . . . . 37217.3 Default immutable set implementations . . . . . . . . . . . 37417.4 Default immutable map implementations . . . . . . . . . . . 374

    31.1 Summary of parser combinators . . . . . . . . . . . . . . . 653

    xix

  • List of Listings

    3.1 Parameterizing an array with a type. . . . . . . . . . . . . 723.2 Creating and initializing an array. . . . . . . . . . . . . . . 753.3 Creating and initializing a list. . . . . . . . . . . . . . . . . 763.4 Creating and using a tuple. . . . . . . . . . . . . . . . . . 803.5 Creating, initializing, and using an immutable set. . . . . . 813.6 Creating, initializing, and using a mutable set. . . . . . . . 833.7 Creating, initializing, and using a mutable map. . . . . . . 843.8 Creating, initializing, and using an immutable map. . . . . 853.9 A function without side effects or vars. . . . . . . . . . . . 873.10 Reading lines from a file. . . . . . . . . . . . . . . . . . . 893.11 Printing formatted character counts for the lines of a file. . 92

    4.1 Final version of class ChecksumAccumulator. . . . . . . . 974.2 Companion object for class ChecksumAccumulator. . . . . 1004.3 The Summer application. . . . . . . . . . . . . . . . . . . . 1024.4 Using the Application trait. . . . . . . . . . . . . . . . . 105

    6.1 Rational with fields. . . . . . . . . . . . . . . . . . . . . 1356.2 Rational with an auxiliary constructor. . . . . . . . . . . 1376.3 Rational with a private field and method. . . . . . . . . . 1386.4 Rational with operator methods. . . . . . . . . . . . . . . 1406.5 Rational with overloaded methods. . . . . . . . . . . . . 145

    7.1 Scala’s idiom for conditional initialization. . . . . . . . . . 1507.2 Calculating greatest common divisor with a while loop. . . 1517.3 Reading from the standard input with do-while. . . . . . . 1527.4 Calculating greatest common divisor with recursion. . . . . 1537.5 Listing files in a directory with a for expression. . . . . . . 154

    xx

  • List of Listings xxi

    7.6 Finding .scala files using a for with a filter. . . . . . . . 1567.7 Using multiple filters in a for expression. . . . . . . . . . 1567.8 Using multiple generators in a for expression. . . . . . . . 1577.9 Mid-stream assignment in a for expression. . . . . . . . . 1587.10 Transforming an Array[File] to Array[Int] with a for. 1597.11 A try-catch clause in Scala. . . . . . . . . . . . . . . . . 1617.12 A try-finally clause in Scala. . . . . . . . . . . . . . . 1627.13 A catch clause that yields a value. . . . . . . . . . . . . . 1637.14 A match expression with side effects. . . . . . . . . . . . . 1647.15 A match expression that yields a value. . . . . . . . . . . . 1647.16 Looping without break or continue. . . . . . . . . . . . . 1667.17 A recursive alternative to looping with vars. . . . . . . . . 1667.18 Variable scoping when printing a multiplication table. . . . 1687.19 A functional way to create a multiplication table. . . . . . . 171

    8.1 LongLines with a private processLine method. . . . . . . 1748.2 LongLines with a local processLine function. . . . . . . 176

    9.1 Using closures to reduce code duplication. . . . . . . . . . 1989.2 Defining and invoking a “plain old” function. . . . . . . . . 2019.3 Defining and invoking a curried function. . . . . . . . . . . 2019.4 Using the loan pattern to write to a file. . . . . . . . . . . . 2059.5 Using a by-name parameter. . . . . . . . . . . . . . . . . . 206

    10.1 Defining an abstract method and class. . . . . . . . . . . . 21110.2 Defining parameterless methods width and height. . . . . 21210.3 Defining ArrayElement as a subclass of Element. . . . . . 21410.4 Overriding a parameterless method with a field. . . . . . . 21610.5 Defining contents as a parametric field. . . . . . . . . . . 21810.6 Invoking a superclass constructor. . . . . . . . . . . . . . . 21910.7 Declaring a final method. . . . . . . . . . . . . . . . . . . 22510.8 Declaring a final class. . . . . . . . . . . . . . . . . . . . . 22510.9 Class Element with above, beside, and toString. . . . . 23010.10 A factory object with factory methods. . . . . . . . . . . . 23110.11 Class Element refactored to use factory methods. . . . . . 23210.12 Hiding implementation with private classes. . . . . . . . . 23310.13 Element with widen and heighten methods. . . . . . . . 23410.14 The Spiral application. . . . . . . . . . . . . . . . . . . . 235

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxi

  • List of Listings xxii

    12.1 The definition of trait Philosophical. . . . . . . . . . . . 24512.2 Mixing in a trait using extends. . . . . . . . . . . . . . . 24612.3 Mixing in a trait using with. . . . . . . . . . . . . . . . . 24712.4 Mixing in multiple traits. . . . . . . . . . . . . . . . . . . 24712.5 Defining an enrichment trait. . . . . . . . . . . . . . . . . 25112.6 Abstract class IntQueue. . . . . . . . . . . . . . . . . . . 25512.7 A BasicIntQueue implemented with an ArrayBuffer. . . 25512.8 The Doubling stackable modification trait. . . . . . . . . . 25612.9 Mixing in a trait when instantiating with new. . . . . . . . . 25712.10 Stackable modification traits Incrementing and Filtering. 257

    13.1 Placing the contents of an entire file into a package. . . . . 26513.2 Nesting multiple packages in the same file. . . . . . . . . . 26513.3 Nesting packages with minimal indentation. . . . . . . . . 26613.4 Scala packages truly nest. . . . . . . . . . . . . . . . . . . 26713.5 Accessing hidden package names. . . . . . . . . . . . . . . 26713.6 Bob’s delightful fruits, ready for import. . . . . . . . . . . 26813.7 Importing the members of a regular (not singleton) object. . 26913.8 Importing a package name. . . . . . . . . . . . . . . . . . 27013.9 How private access differs in Scala and Java. . . . . . . . . 27313.10 How protected access differs in Scala and Java. . . . . . . . 27413.11 Flexible scope of protection with access qualifiers. . . . . . 27513.12 Accessing private members of companion classes and objects. 277

    14.1 Using an assertion. . . . . . . . . . . . . . . . . . . . . . . 28014.2 Using ensuring to assert a function’s result. . . . . . . . . 28014.3 Writing a test method with Suite. . . . . . . . . . . . . . 28114.4 Writing a test function with FunSuite. . . . . . . . . . . . 28214.5 Writing a JUnit test with JUnit3Suite. . . . . . . . . . . 28514.6 Writing a TestNG test with TestNGSuite. . . . . . . . . . 28614.7 Specifying and testing behavior with a ScalaTest Spec. . . 28714.8 Specifying and testing behavior with the specs framework. . 28814.9 Writing property-based tests with ScalaCheck. . . . . . . . 28914.10 Checking properties from a JUnit TestCase with Checkers. 290

    15.1 Defining case classes. . . . . . . . . . . . . . . . . . . . . 29415.2 The simplifyTop function, which does a pattern match. . . 29615.3 A pattern match with an empty “default” case. . . . . . . . 297

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxii

  • List of Listings xxiii

    15.4 A pattern match with wildcard patterns. . . . . . . . . . . . 29815.5 A pattern match with constant patterns. . . . . . . . . . . . 29915.6 A pattern match with a variable pattern. . . . . . . . . . . . 30015.7 A pattern match with a constructor pattern. . . . . . . . . . 30215.8 A sequence pattern with a fixed length. . . . . . . . . . . . 30215.9 A sequence pattern with an arbitrary length. . . . . . . . . 30315.10 A pattern match with a tuple pattern. . . . . . . . . . . . . 30315.11 A pattern match with typed patterns. . . . . . . . . . . . . 30315.12 Using isInstanceOf and asInstanceOf (poor style). . . . 30515.13 A pattern with a variable binding (via the @ sign). . . . . . 30715.14 A match expression with a pattern guard. . . . . . . . . . . 30815.15 Match expression in which case order matters. . . . . . . . 30915.16 A sealed hierarchy of case classes. . . . . . . . . . . . . . 31115.17 Defining multiple variables with one assignment. . . . . . . 31415.18 A for expression with a tuple pattern. . . . . . . . . . . . 31815.19 Picking elements of a list that match a pattern. . . . . . . . 31815.20 The top half of the expression formatter. . . . . . . . . . . 32115.21 The bottom half of the expression formatter. . . . . . . . . 32215.22 An application that prints formatted expressions. . . . . . . 325

    16.1 A merge sort function for Lists. . . . . . . . . . . . . . . 342

    17.1 Default map and set definitions in Predef. . . . . . . . . . 36817.2 Mixing in the SynchronizedMap trait. . . . . . . . . . . . 376

    18.1 A mutable bank account class. . . . . . . . . . . . . . . . . 38818.2 A class with public vars. . . . . . . . . . . . . . . . . . . 39018.3 How public vars are expanded into getter and setter methods. 39118.4 Defining getter and setter methods directly. . . . . . . . . . 39118.5 Defining a getter and setter without an associated field. . . 39218.6 The halfAdder method. . . . . . . . . . . . . . . . . . . . 39518.7 The fullAdder method. . . . . . . . . . . . . . . . . . . . 39618.8 The Simulation class. . . . . . . . . . . . . . . . . . . . 39818.9 The first half of the BasicCircuitSimulation class. . . . 40218.10 The second half of the BasicCircuitSimulation class. . 40318.11 The CircuitSimulation class. . . . . . . . . . . . . . . . 407

    19.1 A basic functional queue. . . . . . . . . . . . . . . . . . . 41319.2 Hiding a primary constructor by making it private. . . . . . 414

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxiii

  • List of Listings xxiv

    19.3 An apply factory method in a companion object. . . . . . . 41519.4 Type abstraction for functional queues. . . . . . . . . . . . 41619.5 A nonvariant (rigid) Cell class. . . . . . . . . . . . . . . . 41919.6 A type parameter with a lower bound. . . . . . . . . . . . . 42519.7 A contravariant output channel. . . . . . . . . . . . . . . . 42619.8 Covariance and contravariance of Function1s. . . . . . . . 42719.9 Demonstration of function type parameter variance. . . . . 42819.10 An optimized functional queue. . . . . . . . . . . . . . . . 43019.11 A Person class that mixes in the Ordered trait. . . . . . . 43219.12 A merge sort function with an upper bound. . . . . . . . . 432

    20.1 Overriding abstract vals and parameterless methods. . . . 43820.2 Declaring abstract vars. . . . . . . . . . . . . . . . . . . . 43820.3 How abstract vars are expanded into getters and setters. . . 43920.4 A trait that uses its abstract vals. . . . . . . . . . . . . . . 44020.5 Pre-initialized fields in an anonymous class expression. . . 44220.6 Pre-initialized fields in an object definition. . . . . . . . . . 44220.7 Pre-initialized fields in a class definition. . . . . . . . . . . 44320.8 Initializing a trait with lazy vals. . . . . . . . . . . . . . . 44420.9 Modeling suitable food with an abstract type. . . . . . . . . 44820.10 Implementing an abstract type in a subclass. . . . . . . . . 44920.11 The US currency zone. . . . . . . . . . . . . . . . . . . . . 45920.12 Currency zones for Europe and Japan. . . . . . . . . . . . 46020.13 A converter object with an exchange rates map. . . . . . . 46120.14 The full code of class CurrencyZone. . . . . . . . . . . . 462

    21.1 An implicit parameter list with multiple parameters. . . . . 47721.2 A function with an upper bound. . . . . . . . . . . . . . . 47921.3 A function with an implicit parameter. . . . . . . . . . . . 48021.4 A function that uses an implicit parameter internally. . . . . 48221.5 A function with a view bound. . . . . . . . . . . . . . . . . 48321.6 Sample code that uses an implicit parameter. . . . . . . . . 48421.7 Sample code after type checking and insertion of implicits. 484

    22.1 The definition of the Nil singleton object. . . . . . . . . . 48922.2 Prepending a supertype element to a subtype list. . . . . . . 49122.3 The definition of method :: (cons) in class List. . . . . . 49122.4 The definition of method ::: in class List. . . . . . . . . 493

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxiv

  • List of Listings xxv

    22.5 The definition of method map in class List. . . . . . . . . 49522.6 The definition of the :: subclass of List. . . . . . . . . . 496

    24.1 The EMail string extractor object. . . . . . . . . . . . . . . 51824.2 The Twice string extractor object. . . . . . . . . . . . . . . 52124.3 The UpperCase string extractor object. . . . . . . . . . . . 52124.4 The Domain string extractor object. . . . . . . . . . . . . . 52324.5 The ExpandedEMail extractor object. . . . . . . . . . . . . 52424.6 Hiding a primary constructor by making it private. . . . . . 52524.7 How the r method is defined in RichString. . . . . . . . . 529

    27.1 A simple Food entity class. . . . . . . . . . . . . . . . . . 55527.2 Simple Recipe entity class. . . . . . . . . . . . . . . . . . 55627.3 Food and Recipe examples for use in tests. . . . . . . . . . 55627.4 Mock database and browser modules. . . . . . . . . . . . . 55727.5 Database and browser modules with categories added. . . . 55827.6 A Browser class with an abstract database val. . . . . . . 55927.7 A Database class with abstract methods. . . . . . . . . . . 56027.8 The SimpleDatabase object as a Database subclass. . . . 56027.9 The SimpleBrowser object as a Browser subclass. . . . . 56127.10 A student database and browser. . . . . . . . . . . . . . . . 56127.11 A trait for food categories. . . . . . . . . . . . . . . . . . . 56227.12 A Database class that mixes in the FoodCategories trait. 56227.13 A SimpleDatabase object composed solely of mixins. . . 56227.14 A SimpleFoods trait. . . . . . . . . . . . . . . . . . . . . 56227.15 A SimpleRecipes trait with a self type. . . . . . . . . . . 56327.16 An app that dynamically selects a module implementation. 56427.17 Using a singleton type. . . . . . . . . . . . . . . . . . . . 566

    28.1 A superclass equals method that calls canEqual. . . . . . 58028.2 A subclass equals method that calls canEqual. . . . . . . 58128.3 Hierarchy for binary trees. . . . . . . . . . . . . . . . . . . 58328.4 A parameterized type with equals and hashCode. . . . . . 58728.5 Class Rational with equals and hashCode. . . . . . . . . 588

    29.1 A Scala method that declares a Java throws clause. . . . . 599

    30.1 A simple actor. . . . . . . . . . . . . . . . . . . . . . . . . 60930.2 An actor that calls receive. . . . . . . . . . . . . . . . . . 611

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxv

  • List of Listings xxvi

    30.3 An actor that calls react. . . . . . . . . . . . . . . . . . . 61530.4 An actor’s act method that uses loop. . . . . . . . . . . . 61630.5 An actor that uses a helper actor to avoid blocking itself. . . 61830.6 An actor that uses case classes for messages. . . . . . . . . 62330.7 The Simulant trait. . . . . . . . . . . . . . . . . . . . . . 63130.8 Adder components. . . . . . . . . . . . . . . . . . . . . . 638

    31.1 An arithmetic expression parser. . . . . . . . . . . . . . . . 64431.2 A regular expression parser for Java identifiers. . . . . . . . 64631.3 Data in JSON format. . . . . . . . . . . . . . . . . . . . . 64831.4 A simple JSON parser. . . . . . . . . . . . . . . . . . . . . 64831.5 A full JSON parser that returns meaningful results. . . . . . 65331.6 The ~ combinator method. . . . . . . . . . . . . . . . . . . 661

    32.1 A simple Swing application in Scala. . . . . . . . . . . . . 67232.2 Component assembly on a panel. . . . . . . . . . . . . . . 67432.3 Implementing a reactive Swing application. . . . . . . . . . 67832.4 An implementation of the temperature converter. . . . . . . 680

    33.1 Code for spreadsheet in Figure 33.1. . . . . . . . . . . . . 68533.2 The main program for the spreadsheet application. . . . . . 68633.3 A spreadsheet with a rendererComponent method. . . . . 68733.4 First version of the Model class. . . . . . . . . . . . . . . . 68833.5 Classes representing formulas. . . . . . . . . . . . . . . . 69033.6 A spreadsheet that parses formulas. . . . . . . . . . . . . . 69433.7 The evaluate method of trait Evaluator. . . . . . . . . . 69733.8 A library for arithmetic operations. . . . . . . . . . . . . . 69933.9 The finished spreadsheet component. . . . . . . . . . . . . 705

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxvi

  • Foreword

    Martin Odersky made a huge impact on the Java world with his design of thePizza language. Although Pizza itself never became popular, it demonstratedthat object-oriented and functional language features, when combined withskill and taste, form a natural and powerful combination. Pizza’s design be-came the basis for generics in Java, and Martin’s GJ (Generic Java) compilerwas Sun Microsystem’s standard compiler starting in 1.3 (though with gener-ics disabled). I had the pleasure of maintaining this compiler for a numberof years, so I can report from first-hand experience that Martin’s skill in lan-guage design extends to language implementation.

    Since that time, we at Sun tried to simplify program development by ex-tending the language with piecemeal solutions to particular problems, likethe for-each loop, enums, and autoboxing. Meanwhile, Martin continued hiswork on more powerful orthogonal language primitives that allow program-mers to provide solutions in libraries.

    Lately, there has been a backlash against statically typed languages. Ex-perience with Java has shown that programming in a static language resultsin an abundance of boilerplate. The common wisdom is that one must aban-don static typing to eliminate the boilerplate, and there is a rising interestin dynamic languages such as Python, Ruby, and Groovy. This commonwisdom is debunked by the existence of Martin’s latest brainchild, Scala.

    Scala is a tastefully typed language: it is statically typed, but explicittypes appear in just the right places. Scala takes powerful features fromobject-oriented and functional languages, and combines them with a fewnovel ideas in a beautifully coherent whole. The syntax is so lightweight,and its primitives so expressive, that APIs can be used with virtually no syn-tactic overhead at all. Examples can be found in standard libraries suchas parser combinators and actors. In this sense Scala supports embeddeddomain-specific languages.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxvii

  • Foreword xxviii

    Will Scala be the next great language? Only time will tell. Martin Oder-sky’s team certainly has the taste and skill for the job. One thing is sure:Scala sets a new standard against which future languages will be measured.

    Neal GafterSan Jose, CaliforniaSeptember 3, 2008

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxviii

  • Acknowledgments

    Many people have contributed to this book and to the material it covers. Weare grateful to all of them.

    Scala itself has been a collective effort of many people. The design andthe implementation of version 1.0 was helped by Philippe Altherr, VincentCremet, Gilles Dubochet, Burak Emir, Stéphane Micheloud, Nikolay Mi-haylov, Michel Schinz, Erik Stenman, and Matthias Zenger. Iulian Dragos,Gilles Dubochet, Philipp Haller, Sean McDirmid, Ingo Maier, and AdriaanMoors joined in the effort to develop the second and current version of thelanguage and tools.

    Gilad Bracha, Craig Chambers, Erik Ernst, Matthias Felleisen, ShriramKrishnamurti, Gary Leavens, Sebastian Maneth, Erik Meijer, David Pol-lak, Jon Pretty, Klaus Ostermann, Didier Rémy, Vijay Saraswat, Don Syme,Mads Torgersen, Philip Wadler, Jamie Webb, and John Williams have shapedthe design of the language by graciously sharing their ideas with us in livelyand inspiring discussions, as well as through comments on previous versionsof this document. The contributors to the Scala mailing list have also givenvery useful feedback that helped us improve the language and its tools.

    George Berger has worked tremendously to make the build process andthe web presence for the book work smoothly. As a result this project hasbeen delightfully free of technical snafus.

    Many people gave us valuable feedback on early versions of the text.Thanks goes to Eric Armstrong, George Berger, Alex Blewitt, Gilad Bracha,William Cook, Bruce Eckel, Stéphane Micheloud, Todd Millstein, DavidPollak, Frank Sommers, Philip Wadler, and Matthias Zenger. Thanks also tothe Silicon Valley Patterns group for their very helpful review: Dave Astels,Tracy Bialik, John Brewer, Andrew Chase, Bradford Cross, Raoul Duke,John P. Eurich, Steven Ganz, Phil Goodwin, Ralph Jocham, Yan-Fa Li, TaoMa, Jeffery Miller, Suresh Pai, Russ Rufer, Dave W. Smith, Scott Turnquest,

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxix

  • Acknowledgments xxx

    Walter Vannini, Darlene Wallach, and Jonathan Andrew Wolter. And we’dlike to thank Dewayne Johnson and Kim Leedy for their help with the coverart, and Frank Sommers for his work on the index.

    We’d also like to extend a special thanks to all of our readers who con-tributed comments. Your comments were very helpful to us in shaping thisinto an even better book. We couldn’t print the names of everyone who con-tributed comments, but here are the names of readers who submitted at leastfive comments during the eBook PrePrint™ stage by clicking on the Suggestlink, sorted first by the highest total number of comments submitted, thenalphabetically. Thanks goes to: David Biesack, Donn Stephan, Mats Hen-ricson, Rob Dickens, Blair Zajac, Tony Sloane, Nigel Harrison, Javier DiazSoto, William Heelan, Justin Forder, Gregor Purdy, Colin Perkins, BjarteS. Karlsen, Ervin Varga, Eric Willigers, Mark Hayes, Martin Elwin, CalumMacLean, Jonathan Wolter, Les Pruszynski, Seth Tisue, Andrei Formiga,Dmitry Grigoriev, George Berger, Howard Lovatt, John P. Eurich, MariusScurtescu, Jeff Ervin, Jamie Webb, Kurt Zoglmann, Dean Wampler, NikolajLindberg, Peter McLain, Arkadiusz Stryjski, Shanky Surana, Craig Borde-lon, Alexandre Patry, Filip Moens, Fred Janon, Jeff Heon, Boris Lorbeer,Jim Menard, Tim Azzopardi, Thomas Jung, Walter Chang, Jeroen Dijkmei-jer, Casey Bowman, Martin Smith, Richard Dallaway, Antony Stubbs, LarsWestergren, Maarten Hazewinkel, Matt Russell, Remigiusz Michalowski,Andrew Tolopko, Curtis Stanford, Joshua Cough, Zemian Deng, Christo-pher Rodrigues Macias, Juan Miguel Garcia Lopez, Michel Schinz, PeterMoore, Randolph Kahle, Vladimir Kelman, Daniel Gronau, Dirk Detering,Hiroaki Nakamura, Ole Hougaard, Bhaskar Maddala, David Bernard, DerekMahar, George Kollias, Kristian Nordal, Normen Mueller, Rafael Ferreira,Binil Thomas, John Nilsson, Jorge Ortiz, Marcus Schulte, Vadim Gerassi-mov, Cameron Taggart, Jon-Anders Teigen, Silvestre Zabala, Will McQueen,and Sam Owen.

    Lastly, Bill would also like to thank Gary Cornell, Greg Doench, AndyHunt, Mike Leonard, Tyler Ortman, Bill Pollock, Dave Thomas, and AdamWright for providing insight and advice on book publishing.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxx

  • Introduction

    This book is a tutorial for the Scala programming language, written by peo-ple directly involved in the development of Scala. Our goal is that by readingthis book, you can learn everything you need to be a productive Scala pro-grammer. All examples in this book compile with Scala version 2.7.2.

    Who should read this book

    The main target audience for this book is programmers who want to learnto program in Scala. If you want to do your next software project in Scala,then this is the book for you. In addition, the book should be interesting toprogrammers wishing to expand their horizons by learning new concepts. Ifyou’re a Java programmer, for example, reading this book will expose youto many concepts from functional programming as well as advanced object-oriented ideas. We believe learning about Scala, and the ideas behind it, canhelp you become a better programmer in general.

    General programming knowledge is assumed. While Scala is a fine firstprogramming language, this is not the book to use to learn programming.

    On the other hand, no specific knowledge of programming languages isrequired. Even though most people use Scala on the Java platform, this bookdoes not presume you know anything about Java. However, we expect manyreaders to be familiar with Java, and so we sometimes compare Scala to Javato help such readers understand the differences.

    How to use this book

    Because the main purpose of this book is to serve as a tutorial, the recom-mended way to read this book is in chapter order, from front to back. Wehave tried hard to introduce one topic at a time, and explain new topics only

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxi

  • Introduction xxxii

    in terms of topics we’ve already introduced. Thus, if you skip to the backto get an early peek at something, you may find it explained in terms ofconcepts you don’t quite understand. To the extent you read the chaptersin order, we think you’ll find it quite straightforward to gain competency inScala, one step at a time.

    If you see a term you do not know, be sure to check the glossary andthe index. Many readers will skim parts of the book, and that is just fine.The glossary and index can help you backtrack whenever you skim oversomething too quickly.

    After you have read the book once, it should also serve as a languagereference. There is a formal specification of the Scala language, but the lan-guage specification tries for precision at the expense of readability. Althoughthis book doesn’t cover every detail of Scala, it is quite comprehensive andshould serve as an approachable language reference as you become moreadept at programming in Scala.

    How to learn Scala

    You will learn a lot about Scala simply by reading this book from cover tocover. You can learn Scala faster and more thoroughly, though, if you do afew extra things.

    First of all, you can take advantage of the many program examples in-cluded in the book. Typing them in yourself is a way to force your mindthrough each line of code. Trying variations is a way to make them more funand to make sure you really understand how they work.

    Second, keep in touch with the numerous online forums. That way, youand other Scala enthusiasts can help each other. There are numerous mailinglists, discussion forums, a chat room, a wiki, and multiple Scala-specificarticle feeds. Take some time to find ones that fit your information needs.You will spend a lot less time stuck on little problems, so you can spendyour time on deeper, more important questions.

    Finally, once you have read enough, take on a programming project ofyour own. Work on a small program from scratch, or develop an add-in to alarger program. You can only go so far by reading.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxii

  • Introduction xxxiii

    EBook features

    This book is available in both paper and PDF eBook form. The eBook is notsimply an electronic copy of the paper version of the book. While the contentis the same as in the paper version, the eBook has been carefully designedand optimized for reading on a computer screen.

    The first thing to notice is that most references within the eBook arehyperlinked. If you select a reference to a chapter, figure, or glossary entry,your PDF viewer should take you immediately to the selected item so thatyou do not have to flip around to find it.

    Additionally, at the bottom of each page in the eBook are a number ofnavigation links. The “Cover,” “Overview,” and “Contents” links take you tothe front matter of the book. The “Glossary” and “Index” links take you toreference parts of the book. Finally, the “Discuss” link takes you to an onlineforum where you discuss questions with other readers, the authors, and thelarger Scala community. If you find a typo, or something you think could beexplained better, please click on the “Suggest” link, which will take you toan online web application where you can give the authors feedback.

    Although the same pages appear in the eBook as the printed book, blankpages are removed and the remaining pages renumbered. The pages are num-bered differently so that it is easier for you to determine PDF page numberswhen printing only a portion of the eBook. The pages in the eBook are,therefore, numbered exactly as your PDF viewer will number them.

    Typographic conventions

    The first time a term is used, it is italicized. Small code examples, such asx + 1, are written inline with a mono-spaced font. Larger code examples areput into mono-spaced quotation blocks like this:

    def hello() {

    println("Hello, world!")

    }

    When interactive shells are shown, responses from the shell are shown in alighter font.

    scala> 3 + 4

    res0: Int = 7

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxiii

  • Introduction xxxiv

    Content overview

    • Chapter 1, “A Scalable Language,” gives an overview of Scala’s designas well as the reasoning, and history, behind it.

    • Chapter 2, “First Steps in Scala,” shows you how to do a number of ba-sic programming tasks in Scala, without going into great detail abouthow they work. The goal of this chapter is to get your fingers startedtyping and running Scala code.

    • Chapter 3, “Next Steps in Scala,” shows you several more basic pro-gramming tasks that will help you get up to speed quickly in Scala.After completing this chapter, you should be able to start using Scalafor simple scripting tasks.

    • Chapter 4, “Classes and Objects,” starts the in-depth coverage of Scalawith a description of its basic object-oriented building blocks and in-structions on how to compile and run a Scala application.

    • Chapter 5, “Basic Types and Operations,” covers Scala’s basic types,their literals, the operations you can perform on them, how precedenceand associativity works, and what rich wrappers are.

    • Chapter 6, “Functional Objects,” dives more deeply into the object-oriented features of Scala, using functional (i.e., immutable) rationalnumbers as an example.

    • Chapter 7, “Built-in Control Structures,” shows you how to use Scala’sbuilt-in control structures: if, while, for, try, and match.

    • Chapter 8, “Functions and Closures,” provides in-depth coverage offunctions, the basic building block of functional languages.

    • Chapter 9, “Control Abstraction,” shows how to augment Scala’s basiccontrol structures by defining your own control abstractions.

    • Chapter 10, “Composition and Inheritance,” discusses more of Scala’ssupport for object-oriented programming. The topics are not as funda-mental as those in Chapter 4, but they frequently arise in practice.

    • Chapter 11, “Scala’s Hierarchy,” explains Scala’s inheritance hierar-chy and discusses its universal methods and bottom types.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxiv

  • Introduction xxxv

    • Chapter 12, “Traits,” covers Scala’s mechanism for mixin composi-tion. The chapter shows how traits work, describes common uses, andexplains how traits improve on traditional multiple inheritance.

    • Chapter 13, “Packages and Imports,” discusses issues with program-ming in the large, including top-level packages, import statements, andaccess control modifiers like protected and private.

    • Chapter 14, “Assertions and Unit Testing,” shows Scala’s assertionmechanism and gives a tour of the various tools available for writingtests in Scala.

    • Chapter 15, “Case Classes and Pattern Matching,” introduces twinconstructs that support you when writing regular, non-encapsulateddata structures. Case classes and pattern matching are particularlyhelpful for tree-like recursive data.

    • Chapter 16, “Working with Lists,” explains in detail lists, which areprobably the most commonly used data structure in Scala programs.

    • Chapter 17, “Collections,” shows you how to use the basic Scala col-lections, such as lists, arrays, tuples, sets, and maps.

    • Chapter 18, “Stateful Objects,” explains stateful (i.e., mutable) objects,and the syntax Scala provides to express them. The chapter concludeswith a case study on discrete event simulation, which shows somestateful objects in action.

    • Chapter 19, “Type Parameterization,” explains some of the techniquesfor information hiding introduced in Chapter 13 by means of a con-crete example: the design of a class for purely functional queues. Thechapter builds up to a description of variance of type parameters andhow it interacts with information hiding.

    • Chapter 20, “Abstract Members,” describes all kinds of abstract mem-bers that Scala supports. Not only methods, but also fields and typescan be declared abstract.

    • Chapter 21, “Implicit Conversions and Parameters,” covers two con-structs that can help you omit tedious details from source code, lettingthe compiler supply them instead.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxv

  • Introduction xxxvi

    • Chapter 22, “Implementing Lists,” describes the implementation ofclass List. It is important to understand how lists work in Scala,and furthermore the implementation demonstrates the use of severalof Scala’s features.

    • Chapter 23, “For Expressions Revisited,” shows how for expressionsare translated to invocations of map, flatMap, filter, and foreach.

    • Chapter 24, “Extractors,” shows how to pattern match against arbitraryclasses, not just case classes.

    • Chapter 25, “Annotations,” shows how to work with language exten-sion via annotation. The chapter describes several standard annota-tions and shows you how to make your own.

    • Chapter 26, “Working with XML,” explains how to process XML inScala. The chapter shows you idioms for generating XML, parsing it,and processing it once it is parsed.

    • Chapter 27, “Objects As Modules,” shows how Scala’s objects are richenough to remove the need for a separate modules system.

    • Chapter 28, “Object Equality,” points out several issues to considerwhen writing an equals method. There are several pitfalls to avoid.

    • Chapter 29, “Combining Scala and Java,” discusses issues that arisewhen combining Scala and Java together in the same project, and sug-gests ways to deal with them.

    • Chapter 30, “Actors and Concurrency,” shows you how to use Scala’sactors concurrency library. Although you use the Java Platform’s con-currency primitives and libraries from Scala programs, actors can helpyou avoid the deadlocks and race conditions that plague the traditional“threads and locks” approach to concurrency.

    • Chapter 31, “Combinator Parsing,” shows how to build parsers usingScala’s library of parser combinators.

    • Chapter 32, “GUI Programming,” gives a quick tour of a Scala librarythat simplifies GUI programming with Swing.

    • Chapter 33, “The SCells Spreadsheet,” ties everything together byshowing a complete spreadsheet application written in Scala.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxvi

  • Introduction xxxvii

    Resources

    At http://www.scala-lang.org, the main website for Scala, you’ll findthe latest Scala release and links to documentation and community resources.For a more condensed page of links to Scala resources, visit the website forthis book: http://booksites.artima.com/programming_in_scala. Tointeract with other readers of this book, check out the Programming in ScalaForum, at: http://www.artima.com/forums/forum.jsp?forum=282.

    Source code

    You can download a ZIP file containing the source code of this book, which isreleased under the Apache 2.0 open source license, from the book’s website:http://booksites.artima.com/programming_in_scala.

    Errata

    Although this book has been heavily reviewed and checked, errors will in-evitably slip through. To see a (hopefully short) list of errata for this book,visit http://booksites.artima.com/programming_in_scala/errata.If you find an error, please report it at the above URL, so that we can besure to fix it in a future printing or edition of this book.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=xxxvii

  • Programming in Scala

    println("Hello, reader!")

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=38

  • Chapter 1

    A Scalable Language

    The name Scala stands for “scalable language.” The language is so namedbecause it was designed to grow with the demands of its users. You can applyScala to a wide range of programming tasks, from writing small scripts tobuilding large systems.1

    Scala is easy to get into. It runs on the standard Java platform and in-teroperates seamlessly with all Java libraries. It’s quite a good languagefor writing scripts that pull together Java components. But it can apply itsstrengths even more when used for building large systems and frameworksof reusable components.

    Technically, Scala is a blend of object-oriented and functional program-ming concepts in a statically typed language. The fusion of object-orientedand functional programming shows up in many different aspects of Scala;it is probably more pervasive than in any other widely used language. Thetwo programming styles have complementary strengths when it comes toscalability. Scala’s functional programming constructs make it easy to buildinteresting things quickly from simple parts. Its object-oriented constructsmake it easy to structure larger systems and to adapt them to new demands.The combination of both styles in Scala makes it possible to express newkinds of programming patterns and component abstractions. It also leads toa legible and concise programming style. And because it is so malleable,programming in Scala can be a lot of fun.

    This initial chapter answers the question, “Why Scala?” It gives a high-level view of Scala’s design and the reasoning behind it. After reading thechapter you should have a basic feel for what Scala is and what kinds of

    1Scala is pronounced skah-lah.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=39

  • Section 1.1 Chapter 1 · A Scalable Language 40

    tasks it might help you accomplish. Although this book is a Scala tutorial,this chapter isn’t really part of the tutorial. If you’re eager to start writingsome Scala code, you should jump ahead to Chapter 2.

    1.1 A language that grows on you

    Programs of different sizes tend to require different programming constructs.Consider, for example, the following small Scala program:

    var capital = Map("US" -> "Washington", "France" -> "Paris")

    capital += ("Japan" -> "Tokyo")

    println(capital("France"))

    This program sets up a map from countries to their capitals, modifies the mapby adding a new binding ("Japan" -> "Tokyo"), and prints the capital asso-ciated with the country France.2 The notation in this example is high-level, tothe point, and not cluttered with extraneous semicolons or type annotations.Indeed, the feel is that of a modern “scripting” language like Perl, Python, orRuby. One common characteristic of these languages, which is relevant forthe example above, is that they each support an “associative map” constructin the syntax of the language.

    Associative maps are very useful because they help keep programs leg-ible and concise. However, sometimes you might not agree with their “onesize fits all” philosophy, because you need to control the properties of themaps you use in your program in a more fine-grained way. Scala gives youthis fine-grained control if you need it, because maps in Scala are not lan-guage syntax. They are library abstractions that you can extend and adapt.

    In the above program, you’ll get a default Map implementation, but youcan easily change that. You could for example specify a particular implemen-tation, such as a HashMap or a TreeMap, or you could specify that the mapshould be thread-safe, by mixing in a SynchronizedMap trait. You couldspecify a default value for the map, or you could override any other methodof the map you create. In each case, you can use the same easy access syntaxfor maps as in the example above.

    2Please bear with us if you don’t understand all details of this program. They will beexplained in the next two chapters.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=40

  • Section 1.1 Chapter 1 · A Scalable Language 41

    This example shows that Scala can give you both convenience and flex-ibility. Scala has a set of convenient constructs that help you get startedquickly and let you program in a pleasantly concise style. At the same time,you have the assurance that you will not outgrow the language. You can al-ways tailor the program to your requirements, because everything is basedon library modules that you can select and adapt as needed.

    Growing new types

    Eric Raymond introduced the cathedral and bazaar as two metaphors of soft-ware development.3 The cathedral is a near-perfect building that takes a longtime to build. Once built, it stays unchanged for a long time. The bazaar, bycontrast, is adapted and extended each day by the people working in it. InRaymond’s work the bazaar is a metaphor for open-source software devel-opment. Guy Steele noted in a talk on “growing a language” that the samedistinction can be applied to language design.4 Scala is much more like abazaar than a cathedral, in the sense that it is designed to be extended andadapted by the people programming in it. Instead of providing all constructsyou might ever need in one “perfectly complete” language, Scala puts thetools for building such constructs into your hands.

    Here’s an example. Many applications need a type of integer that canbecome arbitrarily large without overflow or “wrap-around” of arithmeticoperations. Scala defines such a type in library class scala.BigInt. Hereis the definition of a method using that type, which calculates the factorial ofa passed integer value:5

    def factorial(x: BigInt): BigInt =

    if (x == 0) 1 else x * factorial(x - 1)

    Now, if you call factorial(30) you would get:

    265252859812191058636308480000000

    BigInt looks like a built-in type, because you can use integer literals andoperators such as * and - with values of that type. Yet it is just a class that

    3Raymond, The Cathedral and the Bazaar. [Ray99]4Steele, “Growing a language.” [Ste99]5factorial(x), or x! in mathematical notation, is the result of computing

    1 * 2 * ... * x, with 0! defined to be 1.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · IndexPrep

    ared

    for t

    etsu

    soh

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=41

  • Section 1.1 Chapter 1 · A Scalable Language 42

    happens to be defined in Scala’s standard library.6 If the class were missing,it would be straightforward for any Scala programmer to write an implemen-tation, for instance, by wrapping Java’s class java.math.BigInteger (infact that’s how Scala’s BigInt class is implemented).

    Of course, you could also use Java’s class directly. But the result is notnearly as pleasant, because although Java allows you to create new types,those types don’t feel much like native language support:

    import java.math.BigInteger

    def factorial(x: BigInteger): BigInteger =

    if (x == BigInteger.ZERO)

    BigInteger.ONE

    else

    x.multiply(factorial(x.subtract(BigInteger.ONE)))

    BigInt is representative of many other number-like types—big decimals,complex numbers, rational numbers, confidence intervals, polynomials—thelist goes on. Some programming languages implement some of these typesnatively. For instance, Lisp, Haskell, and Python implement big integers;Fortran and Python implement complex numbers. But any language thatattempted to implement all of these abstractions at the same time would sim-ply become too big to be manageable. What’s more, even if such a languagewere to exist, some applications would surely benefit from other number-like types that were not supplied. So the approach of attempting to provideeverything in one language doesn’t scale very well. Instead, Scala allowsusers to grow and adapt the language in the directions they need by definingeasy-to-use libraries that feel like native language support.

    Growing new control constructs

    The previous example demonstrates that Scala lets you add new types thatcan be used as conveniently as built-in types. The same extension principlealso applies to control structures. This kind of extensibility is illustrated byScala’s API for “actor-based” concurrent programming.

    6Scala comes with a standard library, some of which will be covered in this book. Formore information, you can also consult the library’s Scaladoc documentation, which is avail-able in the distribution and online at http://www.scala-lang.org.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=42

  • Section 1.1 Chapter 1 · A Scalable Language 43

    As multicore processors proliferate in the coming years, achieving ac-ceptable performance may increasingly require that you exploit more paral-lelism in your applications. Often, this will mean rewriting your code so thatcomputations are distributed over several concurrent threads. Unfortunately,creating dependable multi-threaded applications has proven challenging inpractice. Java’s threading model is built around shared memory and locking,a model that is often difficult to reason about, especially as systems scale upin size and complexity. It is hard to be sure you don’t have a race condi-tion or deadlock lurking—something that didn’t show up during testing, butmight just show up in production. An arguably safer alternative is a mes-sage passing architecture such as the “actors” approach used by the Erlangprogramming language.

    Java comes with a rich, thread-based concurrency library. Scala pro-grams can use it like any other Java API. However, Scala also offers an ad-ditional library that essentially implements Erlang’s actor model.

    Actors are concurrency abstractions that can be implemented on top ofthreads. They communicate by sending messages to each other. An actor canperform two basic operations, message send and receive. The send operation,denoted by an exclamation point (!), sends a message to an actor. Here’s anexample in which the actor is named recipient:

    recipient ! msg

    A send is asynchronous; that is, the sending actor can proceed immediately,without waiting for the message to be received and processed. Every actorhas a mailbox in which incoming messages are queued. An actor handlesmessages that have arrived in its mailbox via a receive block:

    receive {

    case Msg1 => ... // handle Msg1

    case Msg2 => ... // handle Msg2

    // ...

    }

    A receive block consists of a number of cases that each query the mailboxwith a message pattern. The first message in the mailbox that matches any ofthe cases is selected, and the corresponding action is performed on it. If themailbox does not contain any messages that match one of the given cases,the actor suspends and waits for further incoming messages.

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=43

  • Section 1.1 Chapter 1 · A Scalable Language 44

    As an example, here is a simple Scala actor implementing a checksumcalculator service:

    actor {

    var sum = 0

    loop {

    receive {

    case Data(bytes) => sum += hash(bytes)

    case GetSum(requester) => requester ! sum

    }

    }

    }

    This actor first defines a local variable named sum with initial value zero. Itthen repeatedly waits in a loop for messages, using a receive statement. If itreceives a Data message, it adds a hash of the sent bytes to the sum variable.If it receives a GetSum message, it sends the current value of sum back to therequester using the message send requester ! sum. The requester fieldis embedded in the GetSum message; it usually refers to the actor that madethe request.

    We don’t expect you to understand fully the actor example at this point.Rather, what’s significant about this example for the topic of scalability isthat neither actor nor loop nor receive nor message send (!) are built-inoperations in Scala. Even though actor, loop, and receive look and actvery much like built-in control constructs such as while or for loops, theyare in fact methods defined in Scala’s actors library. Likewise, even though‘!’ looks like a built-in operator, it too is just a method defined in the actorslibrary. All four of these constructs are completely independent of the Scalaprogramming language.

    The receive block and send (!) syntax look in Scala much like theylook in Erlang, but in Erlang, these constructs are built into the language.Scala also implements most of Erlang’s other concurrent programming con-structs, such as monitoring failed actors and time-outs. All in all, actors haveturned out to be a very pleasant means for expressing concurrent and dis-tributed computations. Even though they are defined in a library, actors feellike an integral part of the Scala language.

    This example illustrates that you can “grow” the Scala language in newdirections even as specialized as concurrent programming. To be sure, youneed good architects and programmers to do this. But the crucial thing is

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=44

  • Section 1.2 Chapter 1 · A Scalable Language 45

    that it is feasible—you can design and implement abstractions in Scala thataddress radically new application domains, yet still feel like native languagesupport.

    1.2 What makes Scala scalable?

    Scalability is influenced by many factors, ranging from syntax details tocomponent abstraction constructs. If we were forced to name just one as-pect of Scala that helps scalability, though, we’d pick its combination ofobject-oriented and functional programming (well, we cheated, that’s reallytwo aspects, but they are intertwined).

    Scala goes further than all other well-known languages in fusing object-oriented and functional programming into a uniform language design. Forinstance, where other languages might have objects and functions as two dif-ferent concepts, in Scala a function value is an object. Function types areclasses that can be inherited by subclasses. This might seem nothing morethan an academic nicety, but it has deep consequences for scalability. In factthe actor concept shown previously could not have been implemented with-out this unification of functions and objects. This section gives an overviewof Scala’s way of blending object-oriented and functional concepts.

    Scala is object-oriented

    Object-oriented programming has been immensely successful. Starting fromSimula in the mid-60’s and Smalltalk in the 70’s, it is now available in morelanguages than not. In some domains objects have taken over completely.While there is not a precise definition of what object-oriented means, thereis clearly something about objects that appeals to programmers.

    In principle, the motivation for object-oriented programming is very sim-ple: all but the most trivial programs need some sort of structure. The moststraightforward way to do this is to put data and operations into some form ofcontainers. The great idea of object-oriented programming is to make thesecontainers fully general, so that they can contain operations as well as data,and that they are themselves values that can be stored in other containers, orpassed as parameters to operations. Such containers are called objects. AlanKay, the inventor of Smalltalk, remarked that in this way the simplest objecthas the same construction principle as a full computer: it combines data with

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=45

  • Section 1.2 Chapter 1 · A Scalable Language 46

    operations under a formalized interface.7 So objects have a lot to do withlanguage scalability: the same techniques apply to the construction of smallas well as large programs.

    Even though object-oriented programming has been mainstream for along time, there are relatively few languages that have followed Smalltalkin pushing this construction principle to its logical conclusion. For instance,many languages admit values that are not objects, such as the primitive val-ues in Java. Or they allow static fields and methods that are not membersof any object. These deviations from the pure idea of object-oriented pro-gramming look quite harmless at first, but they have an annoying tendencyto complicate things and limit scalability.

    By contrast, Scala is an object-oriented language in pure form: everyvalue is an object and every operation is a method call. For example, whenyou say 1 + 2 in Scala, you are actually invoking a method named + definedin class Int. You can define methods with operator-like names that clientsof your API can then use in operator notation. This is how the designer ofScala’s actors API enabled you to use expressions such as requester ! sumshown in the previous example: ‘!’ is a method of the Actor class.

    Scala is more advanced than most other languages when it comes to com-posing objects. An example is Scala’s traits. Traits are like interfaces in Java,but they can also have method implementations and even fields. Objects areconstructed by mixin composition, which takes the members of a class andadds the members of a number of traits to them. In this way, different as-pects of classes can be encapsulated in different traits. This looks a bit likemultiple inheritance, but differs when it comes to the details. Unlike a class,a trait can add some new functionality to an unspecified superclass. Thismakes traits more “pluggable” than classes. In particular, it avoids the clas-sical “diamond inheritance” problems of multiple inheritance, which arisewhen the same class is inherited via several different paths.

    Scala is functional

    In addition to being a pure object-oriented language, Scala is also a full-blown functional language. The ideas of functional programming are olderthan (electronic) computers. Their foundation was laid in Alonzo Church’slambda calculus, which he developed in the 1930s. The first functional pro-gramming language was Lisp, which dates from the late 50s. Other popular

    7Kay, “The Early History of Smalltalk.” [Kay96]

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=46

  • Section 1.2 Chapter 1 · A Scalable Language 47

    functional languages are Scheme, SML, Erlang, Haskell, OCaml, and F#.For a long time, functional programming has been a bit on the sidelines,popular in academia, but not that widely used in industry. However, recentyears have seen an increased interest in functional programming languagesand techniques.

    Functional programming is guided by two main ideas. The first idea isthat functions are first-class values. In a functional language, a function is avalue of the same status as, say, an integer or a string. You can pass func-tions as arguments to other functions, return them as results from functions,or store them in variables. You can also define a function inside anotherfunction, just as you can define an integer value inside a function. And youcan define functions without giving them a name, sprinkling your code withfunction literals as easily as you might write integer literals like 42.

    Functions that are first-class values provide a convenient means for ab-stracting over operations and creating new control structures. This general-ization of functions provides great expressiveness, which often leads to verylegible and concise programs. It also plays an important role for scalability.As an example, the receive construct shown previously in the actor exam-ple is an invocation of a method that takes a function as argument. The codeinside the receive construct is a function that is passed unexecuted into thereceive method.

    In most traditional languages, by contrast, functions are not values. Lan-guages that do have function values often relegate them to second-class sta-tus. For example, the function pointers of C and C++ do not have the samestatus as non-functional values in those languages: function pointers canonly refer to global functions, they do not allow you to define first-classnested functions that refer to some values in their environment. Nor do theyallow you to define unnamed function literals.

    The second main idea of functional programming is that the operationsof a program should map input values to output values rather than changedata in place. To see the difference, consider the implementation of stringsin Ruby and in Java. In Ruby, a string is an array of characters. Charac-ters in a string can be changed individually. For instance you can change asemicolon character in a string to a period inside the same string object. InJava and Scala, on the other hand, a string is a sequence of characters in themathematical sense. Replacing a character in a string using an expressionlike s.replace(';', '.') yields a new string object, which is differentfrom s. Another way of expressing this is that strings are immutable in Java

    Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

    http://www.artima.com/forums/forum.jsp?forum=282http://www.artima.com/backtalk/talkback?v=6&n=47

  • Section 1.3 Chapter 1 · A Scalable Language 48

    whereas they are mutable in Ruby. So looking at just strings, Java is a func-tional language, whereas Ruby is not. Immutable data structures are oneof the cornerstones of functional programming. The Scala libraries definemany more immutable data types on top of those found in the Java APIs. Forinstance, Scala has immutable lists, tuples, maps, and sets.

    Another way of stating this second idea of functional programming isthat methods should not have any side effects. They should communicatewith their environment only