Programming in Scala 2nd

883
Programming in Scala artima Martin Odersky Lex Spoon Bill Venners A comprehensive step-by-step guide Second Edition Updated for Scala 2.8 Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Transcript of Programming in Scala 2nd

A comprehensive step-by-step guide

Programming in

ScalaSecond EditionUpdated for Scala 2.8

artima

Martin Odersky Lex Spoon Bill Venners

Cover Overview Contents Discuss Suggest Glossary Index

Praise for the rst edition of Programming in ScalaProgramming in Scala is probably one of the best programming books Ive ever read. I like the writing style, the brevity, and the thorough explanations. The book seems to answer every question as it enters my mindits always one step ahead of me. The authors dont just give you some code and take things for granted. They give you the meat so you really understand whats going on. I really like that. - Ken Egervari, Chief Software Architect Programming in Scala is clearly written, thorough, and easy to follow. It has great examples and useful tips throughout. It has enabled our organization to ramp up on the Scala language quickly and efciently. This book is great for any programmer who is trying to wrap their head around the exibility and elegance of the Scala language. - Larry Morroni, Owner, Morroni Technologies, Inc. The Programming in Scala book serves as an excellent tutorial to the Scala language. Working through the book, it ows well with each chapter building on concepts and examples described in earlier ones. The book takes care to explain the language constructs in depth, often providing examples of how the language differs from Java. As well as the main language, there is also some coverage of libraries such as containers and actors. I have found the book really easy to work through, and it is probably one of the better written technical books I have read recently. I really would recommend this book to any programmer wanting to nd out more about the Scala language. - Matthew Todd Cover Overview Contents Discuss Suggest Glossary Index

iii

I am amazed by the effort undertaken by the authors of Programming in Scala. This book is an invaluable guide to what I like to call Scala the Platform: a vehicle to better coding, a constant inspiration for scalable software design and implementation. If only I had Scala in its present mature state and this book on my desk back in 2003, when co-designing and implementing parts of the Athens 2004 Olympic Games Portal infrastructure! To all readers: No matter what your programming background is, I feel you will nd programming in Scala liberating and this book will be a loyal friend in the journey. - Christos KK Loverdos, Software Consultant, Researcher Programming in Scala is a superb in-depth introduction to Scala, and its also an excellent reference. Id say that it occupies a prominent place on my bookshelf, except that Im still carrying it around with me nearly everywhere I go. - Brian Clapper, President, ArdenTex, Inc. Great book, well written with thoughtful examples. I would recommend it to both seasoned programmers and newbies. - Howard Lovatt The book Programming in Scala is not only about how, but more importantly, why to develop programs in this new programming language. The books pragmatic approach in introducing the power of combining objectoriented and functional programming leaves the reader without any doubts as to what Scala really is. - Dr. Ervin Varga, CEO/founder, EXPRO I.T. Consulting This is a great introduction to functional programming for OO programmers. Learning about FP was my main goal, but I also got acquainted with some nice Scala surprises like case classes and pattern matching. Scala is an intriguing language and this book covers it well. Theres always a ne line to walk in a language introduction book between giving too much or not enough information. I nd Programming in Scala to achieve a perfect balance. - Jeff Heon, Programmer Analyst Cover Overview Contents Discuss Suggest Glossary Index

iv I bought an early electronic version of the Programming in Scala book, by Odersky, Spoon, and Venners, and I was immediately a fan. In addition to the fact that it contains the most comprehensive information about the language, there are a few key features of the electronic format that impressed me. I have never seen links used as well in a PDF, not just for bookmarks, but also providing active links from the table of contents and index. I dont know why more authors dont use this feature, because its really a joy for the reader. Another feature which I was impressed with was links to the forums (Discuss) and a way to send comments (Suggest) to the authors via email. The comments feature by itself isnt all that uncommon, but the simple inclusion of a page number in what is generated to send to the authors is valuable for both the authors and readers. I contributed more comments than I would have if the process would have been more arduous. Read Programming in Scala for the content, but if youre reading the electronic version, denitely take advantage of the digital features that the authors took the care to build in! - Dianne Marsh, Founder/Software Consultant, SRT Solutions Lucidity and technical completeness are hallmarks of any well-written book, and I congratulate Martin Odersky, Lex Spoon, and Bill Venners on a job indeed very well done! The Programming in Scala book starts by setting a strong foundation with the basic concepts and ramps up the user to an intermediate level & beyond. This book is certainly a must buy for anyone aspiring to learn Scala. - Jagan Nambi, Enterprise Architecture, GMAC Financial Services Programming in Scala is a pleasure to read. This is one of those wellwritten technical books that provide deep and comprehensive coverage of the subject in an exceptionally concise and elegant manner. The book is organized in a very natural and logical way. It is equally well suited for a curious technologist who just wants to stay on top of the current trends and a professional seeking deep understanding of the language core features and its design rationales. I highly recommend it to all interested in functional programming in general. For Scala developers, this book is unconditionally a must-read. - Igor Khlystov, Software Architect/Lead Programmer, Greystone Inc.

Cover Overview Contents Discuss Suggest Glossary Index

v The book Programming in Scala outright oozes the huge amount of hard work that has gone into it. Ive never read a tutorial-style book before that accomplishes to be introductory yet comprehensive: in their (misguided) attempt to be approachable and not confuse the reader, most tutorials silently ignore aspects of a subject that are too advanced for the current discussion. This leaves a very bad taste, as one can never be sure as to the understanding one has achieved. There is always some residual magic that hasnt been explained and cannot be judged at all by the reader. This book never does that, it never takes anything for granted: every detail is either sufciently explained or a reference to a later explanation is given. Indeed, the text is extensively cross-referenced and indexed, so that forming a complete picture of a complex topic is relatively easy. - Gerald Loefer, Enterprise Java Architect Programming in Scala by Martin Odersky, Lex Spoon, and Bill Venners: in times where good programming books are rare, this excellent introduction for intermediate programmers really stands out. Youll nd everything here you need to learn this promising language. - Christian Neukirchen

Cover Overview Contents Discuss Suggest Glossary Index

Programming in ScalaSecond Edition

Cover Overview Contents Discuss Suggest Glossary Index

Programming in ScalaSecond EditionMartin Odersky, Lex Spoon, Bill Venners

artimaA RTIMA P RESSWALNUT C REEK , C ALIFORNIA

Cover Overview Contents Discuss Suggest Glossary Index

viiiProgramming in Scala Second Edition Martin Odersky is the creator of the Scala language and a professor at EPFL in Lausanne, Switzerland. Lex Spoon worked on Scala for two years as a post-doc with Martin Odersky. Bill Venners is president of Artima, Inc. Artima Press is an imprint of Artima, Inc. P.O. Box 305, Walnut Creek, California 94597 Copyright 2007-2010 Martin Odersky, Lex Spoon, and Bill Venners. All rights reserved. First edition published as PrePrint eBook 2007 First edition published 2008 Second edition published as PrePrint eBook 2010 Second edition published 2010 Build date of this impression December 13, 2010 Produced in the United States of America No part of this publication may be reproduced, modied, distributed, stored in a retrieval system, republished, displayed, or performed, for commercial or noncommercial purposes or for compensation of any kind without prior written permission from Artima, Inc. All information and materials in this book are provided "as is" and without warranty of any kind. The term Artima and the Artima logo are trademarks or registered trademarks of Artima, Inc. All other company and/or product names may be trademarks or registered trademarks of their owners.

Cover Overview Contents Discuss Suggest Glossary Index

to Nastaran - M.O. to Fay - L.S. to Siew - B.V.

Cover Overview Contents Discuss Suggest Glossary Index

OverviewContents List of Figures List of Tables List of Listings Foreword Foreword to the First Edition Acknowledgments Introduction 1. A Scalable Language 2. First Steps in Scala 3. Next Steps in Scala 4. Classes and Objects 5. Basic Types and Operations 6. Functional Objects 7. Built-in Control Structures 8. Functions and Closures 9. Control Abstraction 10. Composition and Inheritance 11. Scalas Hierarchy 12. Traits 13. Packages and Imports 14. Assertions and Unit Testing 15. Case Classes and Pattern Matching 16. Working with Lists 17. Collections 18. Stateful Objects 19. Type Parameterization 20. Abstract Members 21. Implicit Conversions and Parameters 22. Implementing Lists 23. For Expressions Revisited 24. The Scala Collections API 25. The Architecture of Scala Collections 26. Extractors 27. Annotations 28. Working with XML 29. Modular Programming Using Objects 30. Object Equality 31. Combining Scala and Java 32. Actors and Concurrency 33. Combinator Parsing 34. GUI Programming 35. The SCells Spreadsheet A. Scala Scripts on Unix and Windows Glossary Bibliography About the Authors Indexxi xxii xxiv xxvi xxxiv xxxvi xxxviii xli 49 68 81 103 117 139 159 184 207 222 250 258 277 295 309 344 377 399 422 447 479 503 516 532 607 631 647 655 669 684 710 724 759 788 800 825 826 842 845 846

Cover Overview Contents Discuss Suggest Glossary Index

Contents

Contents List of Figures List of Tables List of Listings Foreword Foreword to the First Edition Acknowledgments Introduction 1 A Scalable Language 1.1 A language that grows on you 1.2 What makes Scala scalable? . 1.3 Why Scala? . . . . . . . . . . 1.4 Scalas roots . . . . . . . . . 1.5 Conclusion . . . . . . . . . .

xi xxii xxiv xxvi xxxiv xxxvi xxxviii xli 49 50 55 58 65 67 68 68 70 72 74 75

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

2

First Steps in Scala Step 1. Learn to use the Scala interpreter . Step 2. Dene some variables . . . . . . Step 3. Dene some functions . . . . . . Step 4. Write some Scala scripts . . . . . Step 5. Loop with while; decide with if

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents Step 6. Iterate with foreach and for . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Next Steps in Scala Step 7. Parameterize arrays with types . . . . Step 8. Use lists . . . . . . . . . . . . . . . . Step 9. Use tuples . . . . . . . . . . . . . . . Step 10. Use sets and maps . . . . . . . . . . . Step 11. Learn to recognize the functional style Step 12. Read lines from a le . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . Classes and Objects 4.1 Classes, elds, and methods 4.2 Semicolon inference . . . . 4.3 Singleton objects . . . . . . 4.4 A Scala application . . . . 4.5 The Application trait . . . 4.6 Conclusion . . . . . . . . . 77 80 81 81 85 90 91 96 99 102 103 103 108 109 112 115 116 117 117 118 125 128 129 131 132 134 137 137 139 139 140 142 143 143

xii

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

4

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

5

Basic Types and Operations 5.1 Some basic types . . . . . . . . . . . 5.2 Literals . . . . . . . . . . . . . . . . 5.3 Operators are methods . . . . . . . . 5.4 Arithmetic operations . . . . . . . . 5.5 Relational and logical operations . . 5.6 Bitwise operations . . . . . . . . . . 5.7 Object equality . . . . . . . . . . . . 5.8 Operator precedence and associativity 5.9 Rich wrappers . . . . . . . . . . . . 5.10 Conclusion . . . . . . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

6

Functional Objects 6.1 A specication for class Rational . . 6.2 Constructing a Rational . . . . . . . 6.3 Reimplementing the toString method 6.4 Checking preconditions . . . . . . . . 6.5 Adding elds . . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 7 Self references . . . . . . Auxiliary constructors . . Private elds and methods Dening operators . . . . Identiers in Scala . . . . Method overloading . . . Implicit conversions . . . A word of caution . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 146 148 149 151 154 156 157 157 159 160 161 164 169 173 175 177 181 183 184 184 186 188 190 191 192 195 199 202 206 207 207 211 213 215

xiii

Built-in Control Structures 7.1 If expressions . . . . . . . . . . . . . . 7.2 While loops . . . . . . . . . . . . . . . 7.3 For expressions . . . . . . . . . . . . . . 7.4 Exception handling with try expressions 7.5 Match expressions . . . . . . . . . . . . 7.6 Living without break and continue . . 7.7 Variable scope . . . . . . . . . . . . . . 7.8 Refactoring imperative-style code . . . . 7.9 Conclusion . . . . . . . . . . . . . . . . Functions and Closures 8.1 Methods . . . . . . . . . . . . 8.2 Local functions . . . . . . . . . 8.3 First-class functions . . . . . . 8.4 Short forms of function literals 8.5 Placeholder syntax . . . . . . . 8.6 Partially applied functions . . . 8.7 Closures . . . . . . . . . . . . 8.8 Special function call forms . . . 8.9 Tail recursion . . . . . . . . . . 8.10 Conclusion . . . . . . . . . . . Control Abstraction 9.1 Reducing code duplication . . 9.2 Simplifying client code . . . 9.3 Currying . . . . . . . . . . . 9.4 Writing new control structures

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

8

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

9

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 9.5 9.6 By-name parameters . . . . . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 218 221 222 222 223 224 227 229 230 232 233 235 237 239 240 242 244 248 249 250 250 254 256 257 258 258 261 262 265 267 271 275 276 277

xiv

10 Composition and Inheritance 10.1 A two-dimensional layout library . . . . . . 10.2 Abstract classes . . . . . . . . . . . . . . . 10.3 Dening parameterless methods . . . . . . . 10.4 Extending classes . . . . . . . . . . . . . . 10.5 Overriding methods and elds . . . . . . . . 10.6 Dening parametric elds . . . . . . . . . . 10.7 Invoking superclass constructors . . . . . . . 10.8 Using override modiers . . . . . . . . . . 10.9 Polymorphism and dynamic binding . . . . 10.10 Declaring nal members . . . . . . . . . . . 10.11 Using composition and inheritance . . . . . 10.12 Implementing above, beside, and toString 10.13 Dening a factory object . . . . . . . . . . . 10.14 Heighten and widen . . . . . . . . . . . . . 10.15 Putting it all together . . . . . . . . . . . . . 10.16 Conclusion . . . . . . . . . . . . . . . . . . 11 Scalas Hierarchy 11.1 Scalas class hierarchy . . . . . . 11.2 How primitives are implemented 11.3 Bottom types . . . . . . . . . . . 11.4 Conclusion . . . . . . . . . . . . 12 Traits 12.1 How traits work . . . . . . . . . 12.2 Thin versus rich interfaces . . . . 12.3 Example: Rectangular objects . . 12.4 The Ordered trait . . . . . . . . 12.5 Traits as stackable modications . 12.6 Why not multiple inheritance? . . 12.7 To trait, or not to trait? . . . . . . 12.8 Conclusion . . . . . . . . . . . . 13 Packages and Imports

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 13.1 13.2 13.3 13.4 13.5 13.6 13.7 Putting code in packages . . . Concise access to related code Imports . . . . . . . . . . . . Implicit imports . . . . . . . Access modiers . . . . . . . Package objects . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 278 282 286 287 292 294 295 295 297 298 300 302 305 306 308 309 309 314 324 325 326 328 330 335 343 344 344 345 345 346 347 349 361 369

xv

14 Assertions and Unit Testing 14.1 Assertions . . . . . . . . . . 14.2 Unit testing in Scala . . . . . 14.3 Informative failure reports . . 14.4 Using JUnit and TestNG . . . 14.5 Tests as specications . . . . 14.6 Property-based testing . . . . 14.7 Organizing and running tests 14.8 Conclusion . . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

15 Case Classes and Pattern Matching 15.1 A simple example . . . . . . . 15.2 Kinds of patterns . . . . . . . . 15.3 Pattern guards . . . . . . . . . 15.4 Pattern overlaps . . . . . . . . 15.5 Sealed classes . . . . . . . . . 15.6 The Option type . . . . . . . . 15.7 Patterns everywhere . . . . . . 15.8 A larger example . . . . . . . . 15.9 Conclusion . . . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

16 Working with Lists 16.1 List literals . . . . . . . . . . . . . . 16.2 The List type . . . . . . . . . . . . 16.3 Constructing lists . . . . . . . . . . . 16.4 Basic operations on lists . . . . . . . 16.5 List patterns . . . . . . . . . . . . . 16.6 First-order methods on class List . . 16.7 Higher-order methods on class List 16.8 Methods of the List object . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 16.9 Processing multiple lists together . . . . . . . . . . . . 16.10 Understanding Scalas type inference algorithm . . . . . 16.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 17 Collections 17.1 Sequences . . . . . . . . . . . . . . . . . . . . 17.2 Sets and maps . . . . . . . . . . . . . . . . . . 17.3 Selecting mutable versus immutable collections 17.4 Initializing collections . . . . . . . . . . . . . . 17.5 Tuples . . . . . . . . . . . . . . . . . . . . . . 17.6 Conclusion . . . . . . . . . . . . . . . . . . . . 18 Stateful Objects 18.1 What makes an object stateful? . . . 18.2 Reassignable variables and properties 18.3 Case study: Discrete event simulation 18.4 A language for digital circuits . . . . 18.5 The Simulation API . . . . . . . . 18.6 Circuit Simulation . . . . . . . . . . 18.7 Conclusion . . . . . . . . . . . . . . 19 Type Parameterization 19.1 Functional queues . . . . . . . 19.2 Information hiding . . . . . . . 19.3 Variance annotations . . . . . . 19.4 Checking variance annotations . 19.5 Lower bounds . . . . . . . . . 19.6 Contravariance . . . . . . . . . 19.7 Object private data . . . . . . . 19.8 Upper bounds . . . . . . . . . 19.9 Conclusion . . . . . . . . . . . 371 372 376 377 377 381 390 392 396 398 399 399 402 405 406 409 413 421 422 422 426 429 433 436 438 441 443 446 447 447 448 449 450 451

xvi

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

20 Abstract Members 20.1 A quick tour of abstract members 20.2 Type members . . . . . . . . . . 20.3 Abstract vals . . . . . . . . . . . 20.4 Abstract vars . . . . . . . . . . . 20.5 Initializing abstract vals . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 20.6 20.7 20.8 20.9 20.10 20.11 Abstract types . . . . . Path-dependent types . Structural subtyping . . Enumerations . . . . . . Case study: Currencies . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 461 464 466 468 478 479 479 482 485 486 489 495 498 501 502 503 503 509 511 513 514 516 517 519 522 524 528 529 531 532 533 535 537

xvii

21 Implicit Conversions and Parameters 21.1 Implicit conversions . . . . . . . . . . 21.2 Rules for implicits . . . . . . . . . . . 21.3 Implicit conversion to an expected type 21.4 Converting the receiver . . . . . . . . 21.5 Implicit parameters . . . . . . . . . . . 21.6 View bounds . . . . . . . . . . . . . . 21.7 When multiple conversions apply . . . 21.8 Debugging implicits . . . . . . . . . . 21.9 Conclusion . . . . . . . . . . . . . . . 22 Implementing Lists 22.1 The List class in principle 22.2 The ListBuffer class . . . 22.3 The List class in practice . 22.4 Functional on the outside . 22.5 Conclusion . . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

23 For Expressions Revisited 23.1 For expressions . . . . . . . . . 23.2 The n-queens problem . . . . . 23.3 Querying with for expressions 23.4 Translation of for expressions . 23.5 Going the other way . . . . . . 23.6 Generalizing for . . . . . . . . 23.7 Conclusion . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

24 The Scala Collections API 24.1 Mutable and immutable collections . . . . . . . . . . . 24.2 Collections consistency . . . . . . . . . . . . . . . . . 24.3 Trait Traversable . . . . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

Contents 24.4 24.5 24.6 24.7 24.8 24.9 24.10 24.11 24.12 24.13 24.14 24.15 24.16 24.17 24.18 24.19 24.20 Trait Iterable . . . . . . . . . . . . . . . . . . . . . The sequence traits Seq, IndexedSeq, and LinearSeq Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . Maps . . . . . . . . . . . . . . . . . . . . . . . . . . Synchronized sets and maps . . . . . . . . . . . . . . Concrete immutable collection classes . . . . . . . . Concrete mutable collection classes . . . . . . . . . . Arrays . . . . . . . . . . . . . . . . . . . . . . . . . Strings . . . . . . . . . . . . . . . . . . . . . . . . . Performance characteristics . . . . . . . . . . . . . . Equality . . . . . . . . . . . . . . . . . . . . . . . . Views . . . . . . . . . . . . . . . . . . . . . . . . . . Iterators . . . . . . . . . . . . . . . . . . . . . . . . Creating collections from scratch . . . . . . . . . . . Conversions between Java and Scala collections . . . Migrating from Scala 2.7 . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542 546 551 557 562 564 571 578 583 584 585 587 593 601 603 605 606 607 608 609 614 630 631 631 632 635 637 640 641 642 646 647 647 648 650

xviii

25 The Architecture of Scala Collections 25.1 Builders . . . . . . . . . . . . . 25.2 Factoring out common operations 25.3 Integrating new collections . . . 25.4 Conclusion . . . . . . . . . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

26 Extractors 26.1 An example: extracting email addresses 26.2 Extractors . . . . . . . . . . . . . . . 26.3 Patterns with zero or one variables . . 26.4 Variable argument extractors . . . . . . 26.5 Extractors and sequence patterns . . . 26.6 Extractors versus case classes . . . . . 26.7 Regular expressions . . . . . . . . . . 26.8 Conclusion . . . . . . . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

27 Annotations 27.1 Why have annotations? . . . . . . . . . . . . . . . . . 27.2 Syntax of annotations . . . . . . . . . . . . . . . . . . 27.3 Standard annotations . . . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

Contents 27.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 28 Working with XML 28.1 Semi-structured data . . . 28.2 XML overview . . . . . . 28.3 XML literals . . . . . . . 28.4 Serialization . . . . . . . 28.5 Taking XML apart . . . . 28.6 Deserialization . . . . . . 28.7 Loading and saving . . . 28.8 Pattern matching on XML 28.9 Conclusion . . . . . . . . 654 655 655 656 657 659 661 662 663 665 668 669 670 671 674 677 680 681 683 684 684 685 698 703 709 710 710 713 718 722 722 723 724

xix

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

29 Modular Programming Using Objects 29.1 The problem . . . . . . . . . . . 29.2 A recipe application . . . . . . . 29.3 Abstraction . . . . . . . . . . . . 29.4 Splitting modules into traits . . . 29.5 Runtime linking . . . . . . . . . 29.6 Tracking module instances . . . . 29.7 Conclusion . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

30 Object Equality 30.1 Equality in Scala . . . . . . . . . . . . . 30.2 Writing an equality method . . . . . . . 30.3 Dening equality for parameterized types 30.4 Recipes for equals and hashCode . . . 30.5 Conclusion . . . . . . . . . . . . . . . . 31 Combining Scala and Java 31.1 Using Scala from Java . . . . . . . 31.2 Annotations . . . . . . . . . . . . 31.3 Existential types . . . . . . . . . . 31.4 Using synchronized . . . . . . . 31.5 Compiling Scala and Java together 31.6 Conclusion . . . . . . . . . . . . . 32 Actors and Concurrency

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 32.1 32.2 32.3 32.4 32.5 32.6 32.7 Trouble in paradise . . . . . . . . . . . . . . . . . . Actors and message passing . . . . . . . . . . . . . Treating native threads as actors . . . . . . . . . . . Better performance through thread reuse . . . . . . Good actors style . . . . . . . . . . . . . . . . . . . A longer example: Parallel discrete event simulation Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724 725 729 730 733 740 757 759 760 762 763 764 766 772 781 782 782 784 786 788 788 791 793 796 798 800 800 803 806 808 813 816 819 823

xx

33 Combinator Parsing 33.1 Example: Arithmetic expressions . . 33.2 Running your parser . . . . . . . . . 33.3 Basic regular expression parsers . . . 33.4 Another example: JSON . . . . . . . 33.5 Parser output . . . . . . . . . . . . . 33.6 Implementing combinator parsers . . 33.7 String literals and regular expressions 33.8 Lexing and parsing . . . . . . . . . . 33.9 Error reporting . . . . . . . . . . . . 33.10 Backtracking versus LL(1) . . . . . . 33.11 Conclusion . . . . . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

34 GUI Programming 34.1 A rst Swing application . . . . . . . . 34.2 Panels and layouts . . . . . . . . . . . 34.3 Handling events . . . . . . . . . . . . 34.4 Example: Celsius/Fahrenheit converter 34.5 Conclusion . . . . . . . . . . . . . . . 35 The SCells Spreadsheet 35.1 The visual framework . . . . . . . . 35.2 Disconnecting data entry and display 35.3 Formulas . . . . . . . . . . . . . . . 35.4 Parsing formulas . . . . . . . . . . . 35.5 Evaluation . . . . . . . . . . . . . . 35.6 Operation libraries . . . . . . . . . . 35.7 Change propagation . . . . . . . . . 35.8 Conclusion . . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents A Scala Scripts on Unix and Windows Glossary Bibliography About the Authors Index 825 826 842 845 846

xxi

Cover Overview Contents Discuss Suggest Glossary Index

List of Figures2.1 2.2 3.1 3.2 3.3 10.1 10.2 10.3 10.4 The basic form of a function denition in Scala. . . . . . . . The syntax of a function literal in Scala. . . . . . . . . . . . All operations are method calls in Scala. . . . . . . . . . . . Class hierarchy for Scala sets. . . . . . . . . . . . . . . . . Class hierarchy for Scala maps. . . . . . . . . . . . . . . . . Class diagram for ArrayElement. . . . . . Class diagram for LineElement. . . . . . . Class hierarchy of layout elements. . . . . . Class hierarchy with revised LineElement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 79 84 92 94 228 233 236 240 252 274 307 406 408 409 441 504 508 536 625

11.1 Class hierarchy of Scala. . . . . . . . . . . . . . . . . . . . 12.1 Inheritance hierarchy and linearization of class Cat. . . . . . 14.1 ScalaTests graphical reporter. . . . . . . . . . . . . . . . . 18.1 Basic gates. . . . . . . . . . . . . . . . . . . . . . . . . . . 18.2 A half-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 18.3 A full-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 19.1 Covariance and contravariance in function type parameters. . 22.1 Class hierarchy for Scala lists. . . . . . . . . . . . . . . . . 22.2 The structure of the Scala lists shown in Listing 22.2. . . . . 24.1 Collection hierarchy. . . . . . . . . . . . . . . . . . . . . . 25.1 An example Patricia trie. . . . . . . . . . . . . . . . . . . . xxii

List of Figures 34.1 A simple Swing application: initial (left) and resized (right). 34.2 A reactive Swing application: initial (left) after clicks (right). 34.3 A converter between degrees Celsius and Fahrenheit. . . . . 35.1 35.2 35.3 35.4 A simple spreadsheet table. . . Cells displaying themselves. . Cells displaying their formulas. Cells that evaluate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789 791 796 801 806 812 818

xxiii

Cover Overview Contents Discuss Suggest Glossary Index

List of Tables3.1 5.1 5.2 5.3 5.4 5.5 12.1 13.1 16.1 17.1 17.2 17.3 17.4 24.1 24.2 24.3 24.4 24.5 24.6 24.7 24.8 24.9 24.10 Some List methods and usages . . . . . . . . . . . . . . . Some basic types . . . . . . . . . . . . . Special character literal escape sequences Operator precedence . . . . . . . . . . . Some rich operations . . . . . . . . . . Rich wrapper classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 118 122 135 138 138 275 290 347 384 386 388 388 539 544 548 551 552 553 558 560 577 586

Linearization of types in Cats hierarchy . . . . . . . . . . Effects of private qualiers on LegOfJourney.distance . Basic list operations . . . . . . . . . . . . . . . . . . . . . Common operations for sets . . . . . . . Common operations for maps . . . . . . Default immutable set implementations . Default immutable map implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Operations in trait Traversable . . . . . . . Operations in trait Iterable . . . . . . . . . Operations in trait Seq . . . . . . . . . . . . Operations in trait Buffer . . . . . . . . . . Operations in trait Set . . . . . . . . . . . . Operations in trait mutable.Set . . . . . . . Operations in trait Map . . . . . . . . . . . . Operations in trait mutable.Map . . . . . . . Operations in trait ConcurrentMap . . . . . . Performance characteristics of sequence types xxiv

List of Tables 24.11 Performance characteristics of set and map types . . . . . . 24.12 Operations in trait Iterator . . . . . . . . . . . . . . . . 24.13 Factory methods for sequences . . . . . . . . . . . . . . . 33.1 Summary of parser combinators . . . . . . . . . . . . . . . 586 595 602 770

xxv

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 4.1 4.2 4.3 4.4 6.1 6.2 6.3 6.4 6.5 7.1 7.2 7.3 7.4 7.5 Parameterizing an array with a type. . . . . . . . . . . . Creating and initializing an array. . . . . . . . . . . . . . Creating and initializing a list. . . . . . . . . . . . . . . . Creating and using a tuple. . . . . . . . . . . . . . . . . Creating, initializing, and using an immutable set. . . . . Creating, initializing, and using a mutable set. . . . . . . Creating, initializing, and using a mutable map. . . . . . Creating, initializing, and using an immutable map. . . . A function without side effects or vars. . . . . . . . . . . Reading lines from a le. . . . . . . . . . . . . . . . . . Printing formatted character counts for the lines of a le. Final version of class ChecksumAccumulator. . . . Companion object for class ChecksumAccumulator. The Summer application. . . . . . . . . . . . . . . . Using the Application trait. . . . . . . . . . . . .Rational with elds. . . . . . . . . . . . Rational with an auxiliary constructor. . Rational with a private eld and method. Rational with operator methods. . . . . . Rational with overloaded methods. . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

82 85 86 90 91 93 94 95 97 99 102 107 110 112 115 145 147 148 150 155 160 161 162 163 164

. . . . . . . . .

. . . . . . . . .

. . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

Scalas idiom for conditional initialization. . . . . . . . Calculating greatest common divisor with a while loop. Reading from the standard input with do-while. . . . . Calculating greatest common divisor with recursion. . . Listing les in a directory with a for expression. . . . . xxvi

List of Listings 7.6 7.7 7.8 7.9 7.10 7.11 7.12 7.13 7.14 7.15 7.16 7.17 7.18 7.19 8.1 8.2 8.3 8.4 9.1 9.2 9.3 9.4 9.5 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 Finding .scala les using a for with a lter. . . . . . . . Using multiple lters in a for expression. . . . . . . . . . Using multiple generators in a for expression. . . . . . . . Mid-stream assignment in a for expression. . . . . . . . . Transforming an Array[File] to Array[Int] with a for. A try-catch clause in Scala. . . . . . . . . . . . . . . . . A try-finally clause in Scala. . . . . . . . . . . . . . . A catch clause that yields a value. . . . . . . . . . . . . . A match expression with side effects. . . . . . . . . . . . . A match expression that yields a value. . . . . . . . . . . . Looping without break or continue. . . . . . . . . . . . . A recursive alternative to looping with vars. . . . . . . . . Variable scoping when printing a multiplication table. . . . A functional way to create a multiplication table. . . . . . .LongLines with a private processLine method. . . . . . . LongLines with a local processLine function. . . . . . .

xxvii 166 166 167 168 169 171 172 173 174 174 176 176 179 182 185 187 201 202 211 214 214 218 219 224 225 227 229 231 232 238 238 243 244 245 246

A parameter with a default value. . . . . . . . . . . . . . . A function with two parameters that have defaults. . . . . . Using closures to reduce code duplication. . Dening and invoking a plain old function. Dening and invoking a curried function. . . Using the loan pattern to write to a le. . . . Using a by-name parameter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Dening an abstract method and class. . . . . . . . Dening parameterless methods width and height. Dening ArrayElement as a subclass of Element. . Overriding a parameterless method with a eld. . . Dening contents as a parametric eld. . . . . . . Invoking a superclass constructor. . . . . . . . . . . Declaring a nal method. . . . . . . . . . . . . . . Declaring a nal class. . . . . . . . . . . . . . . . . Class Element with above, beside, and toString. A factory object with factory methods. . . . . . . . Class Element refactored to use factory methods. . Hiding implementation with private classes. . . . .

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 10.13 Element with widen and heighten methods. . . . . . . . 10.14 The Spiral application. . . . . . . . . . . . . . . . . . . . 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 13.12 13.13 13.14 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 The denition of trait Philosophical. . . . . . . . . . . . Mixing in a trait using extends. . . . . . . . . . . . . . . Mixing in a trait using with. . . . . . . . . . . . . . . . . Mixing in multiple traits. . . . . . . . . . . . . . . . . . . Dening an enrichment trait. . . . . . . . . . . . . . . . . Abstract class IntQueue. . . . . . . . . . . . . . . . . . . A BasicIntQueue implemented with an ArrayBuffer. . . The Doubling stackable modication trait. . . . . . . . . . Mixing in a trait when instantiating with new. . . . . . . . . Stackable modication traits Incrementing and Filtering. Placing the contents of an entire le into a package. . . . . Long form of a simple package declaration. . . . . . . . . Multiple packages in the same le. . . . . . . . . . . . . . Concise access to classes and packages. . . . . . . . . . . . Symbols in enclosing packages not automatically available. Accessing hidden package names. . . . . . . . . . . . . . . Bobs delightful fruits, ready for import. . . . . . . . . . . Importing the members of a regular (not singleton) object. . Importing a package name. . . . . . . . . . . . . . . . . . How private access differs in Scala and Java. . . . . . . . . How protected access differs in Scala and Java. . . . . . . . Flexible scope of protection with access qualiers. . . . . . Accessing private members of companion classes and objects. A package object. . . . . . . . . . . . . . . . . . . . . . . Using an assertion. . . . . . . . . . . . . . . . . . . . . . . Using ensuring to assert a functions result. . . . . . . . . Writing a test method with Suite. . . . . . . . . . . . . . Writing a test function with FunSuite. . . . . . . . . . . . Writing a JUnit test with JUnit3Suite. . . . . . . . . . . Writing a TestNG test with TestNGSuite. . . . . . . . . . Specifying and testing behavior with a ScalaTest FlatSpec. Specifying and testing behavior with the specs framework. . Writing property-based tests with ScalaCheck. . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index 247 248 258 259 260 260 264 268 268 269 270 270 278 278 279 279 280 280 283 283 284 287 288 289 292 293 296 296 297 298 301 302 303 304 305

xxviii

List of Listings 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 15.13 15.14 15.15 15.16 15.17 15.18 15.19 15.20 15.21 15.22 16.1 17.1 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10 18.11 Dening case classes. . . . . . . . . . . . . . . . . . . . The simplifyTop function, which does a pattern match. . A pattern match with an empty default case. . . . . . . A pattern match with wildcard patterns. . . . . . . . . . . A pattern match with constant patterns. . . . . . . . . . . A pattern match with a variable pattern. . . . . . . . . . . A pattern match with a constructor pattern. . . . . . . . . A sequence pattern with a xed length. . . . . . . . . . . A sequence pattern with an arbitrary length. . . . . . . . A pattern match with a tuple pattern. . . . . . . . . . . . A pattern match with typed patterns. . . . . . . . . . . . Using isInstanceOf and asInstanceOf (poor style). . . A pattern with a variable binding (via the @ sign). . . . . A match expression with a pattern guard. . . . . . . . . . Match expression in which case order matters. . . . . . . A sealed hierarchy of case classes. . . . . . . . . . . . . Dening multiple variables with one assignment. . . . . . A for expression with a tuple pattern. . . . . . . . . . . Picking elements of a list that match a pattern. . . . . . . The top half of the expression formatter. . . . . . . . . . The bottom half of the expression formatter. . . . . . . . An application that prints formatted expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 312 314 315 315 316 318 318 319 319 320 321 323 324 325 327 330 334 334 337 338 341 360 382 400 402 403 403 404 407 408 410 414 415 419

xxix

A merge sort function for Lists. . . . . . . . . . . . . . . Default map and set denitions in Predef. . . . . . . . . . A mutable bank account class. . . . . . . . . . . . . . . . . A class with public vars. . . . . . . . . . . . . . . . . . . How public vars are expanded into getter and setter methods. Dening getter and setter methods directly. . . . . . . . . . Dening a getter and setter without an associated eld. . . The halfAdder method. . . . . . . . . . . . . . . . . . . . The fullAdder method. . . . . . . . . . . . . . . . . . . . The Simulation class. . . . . . . . . . . . . . . . . . . . The rst half of the BasicCircuitSimulation class. . . . The second half of the BasicCircuitSimulation class. . The CircuitSimulation class. . . . . . . . . . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 19.10 19.11 19.12 20.1 20.2 20.3 20.4 20.5 20.6 20.7 20.8 20.9 20.10 20.11 20.12 20.13 20.14 21.1 21.2 21.3 21.4 21.5 21.6 21.7 22.1 22.2 A basic functional queue. . . . . . . . . . . . . . . Hiding a primary constructor by making it private. . An apply factory method in a companion object. . . Type abstraction for functional queues. . . . . . . . A nonvariant (rigid) Cell class. . . . . . . . . . . . A type parameter with a lower bound. . . . . . . . . A contravariant output channel. . . . . . . . . . . . Covariance and contravariance of Function1s. . . . Demonstration of function type parameter variance. An optimized functional queue. . . . . . . . . . . . A Person class that mixes in the Ordered trait. . . A merge sort function with an upper bound. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 426 427 428 431 437 438 439 440 442 444 444 450 450 451 452 454 454 455 456 460 461 473 475 476 477 491 493 494 496 497 500 500 505 507

xxx

Overriding abstract vals and parameterless methods. . Declaring abstract vars. . . . . . . . . . . . . . . . . . How abstract vars are expanded into getters and setters. A trait that uses its abstract vals. . . . . . . . . . . . . Pre-initialized elds in an anonymous class expression. Pre-initialized elds in an object denition. . . . . . . . Pre-initialized elds in a class denition. . . . . . . . . Initializing a trait with lazy vals. . . . . . . . . . . . . Modeling suitable food with an abstract type. . . . . . . Implementing an abstract type in a subclass. . . . . . . The US currency zone. . . . . . . . . . . . . . . . . . . Currency zones for Europe and Japan. . . . . . . . . . A converter object with an exchange rates map. . . . . The full code of class CurrencyZone. . . . . . . . . .

An implicit parameter list with multiple parameters. . . . . A function with an upper bound. . . . . . . . . . . . . . . A function with an implicit parameter. . . . . . . . . . . . A function that uses an implicit parameter internally. . . . . A function with a view bound. . . . . . . . . . . . . . . . . Sample code that uses an implicit parameter. . . . . . . . . Sample code after type checking and insertion of implicits. The denition of the Nil singleton object. . . . . . . . . . Prepending a supertype element to a subtype list. . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 22.3 22.4 22.5 22.6 24.1 25.1 25.2 25.3 25.4 25.5 25.6 25.7 25.8 25.9 25.10 25.11 26.1 26.2 26.3 26.4 26.5 26.6 26.7 29.1 29.2 29.3 29.4 29.5 29.6 29.7 29.8 29.9 29.10 29.11 29.12 The denition of method :: (cons) in class List. The denition of method ::: in class List. . . . The denition of method map in class List. . . . The denition of the :: subclass of List. . . . . . . . . . . . . . . . . . . . . . . . . 507 509 511 512 563 608 609 612 612 614 615 618 622 623 626 629 633 636 636 638 639 640 644 671 672 672 673 674 675 676 676 677 677 678 678

xxxi

Mixing in the SynchronizedMap trait. . . . . . . . . . . . An outline of the Builder class. . . . . . . . . . . . Implementation of filter in TraversableLike. . . Implementation of map in TraversableLike. . . . . The CanBuildFrom trait. . . . . . . . . . . . . . . . RNA Bases. . . . . . . . . . . . . . . . . . . . . . . RNA strands class, rst version. . . . . . . . . . . . . RNA strands class, second version. . . . . . . . . . . RNA strands class, nal version. . . . . . . . . . . . RNA companion objectnal version. . . . . . . . . An implementation of prex maps with Patricia tries. The companion object for prex maps. . . . . . . . . The EMail string extractor object. . . . . . . . . . The Twice string extractor object. . . . . . . . . . The UpperCase string extractor object. . . . . . . The Domain string extractor object. . . . . . . . . The ExpandedEMail extractor object. . . . . . . . An extractor that denes an unapplySeq method. How the r method is dened in StringOps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A simple Food entity class. . . . . . . . . . . . . . . . . . Simple Recipe entity class. . . . . . . . . . . . . . . . . . Food and Recipe examples for use in tests. . . . . . . . . . Mock database and browser modules. . . . . . . . . . . . . Database and browser modules with categories added. . . . A Browser class with an abstract database val. . . . . . . A Database class with abstract methods. . . . . . . . . . . The SimpleDatabase object as a Database subclass. . . . The SimpleBrowser object as a Browser subclass. . . . . A student database and browser. . . . . . . . . . . . . . . . A trait for food categories. . . . . . . . . . . . . . . . . . . A Database class that mixes in the FoodCategories trait.

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 29.13 29.14 29.15 29.16 29.17 30.1 30.2 30.3 30.4 30.5 31.1 32.1 32.2 32.3 32.4 32.5 32.6 32.7 32.8 33.1 33.2 33.3 33.4 33.5 33.6 34.1 34.2 34.3 34.4 35.1 35.2 35.3 35.4 A SimpleDatabase object composed solely of mixins. . . A SimpleFoods trait. . . . . . . . . . . . . . . . . . . . . A SimpleRecipes trait with a self type. . . . . . . . . . . An app that dynamically selects a module implementation. Using a singleton type. . . . . . . . . . . . . . . . . . . . A superclass equals method that calls canEqual. A subclass equals method that calls canEqual. . Hierarchy for binary trees. . . . . . . . . . . . . . A parameterized type with equals and hashCode. Class Rational with equals and hashCode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678 678 679 680 682 696 697 699 703 704 715 726 728 732 733 735 740 748 755 761 763 765 766 770 778 789 791 795 797 802 803 804 805

xxxii

A Scala method that declares a Java throws clause. . . . . A simple actor. . . . . . . . . . . . . . . . . . . . . . . An actor that calls receive. . . . . . . . . . . . . . . . An actor that calls react. . . . . . . . . . . . . . . . . An actors act method that uses loop. . . . . . . . . . An actor that uses a helper actor to avoid blocking itself. An actor that uses case classes for messages. . . . . . . The Simulant trait. . . . . . . . . . . . . . . . . . . . Adder components. . . . . . . . . . . . . . . . . . . . An arithmetic expression parser. . . . . . . . . . . A regular expression parser for Java identiers. . . Data in JSON format. . . . . . . . . . . . . . . . A simple JSON parser. . . . . . . . . . . . . . . . A full JSON parser that returns meaningful results. The ~ combinator method. . . . . . . . . . . . . . A simple Swing application in Scala. . . . . . . Component assembly on a panel. . . . . . . . . Implementing a reactive Swing application. . . . An implementation of the temperature converter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Code for spreadsheet in Figure 35.1. . . . . . . . . The main program for the spreadsheet application. . A spreadsheet with a rendererComponent method. First version of the Model class. . . . . . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 35.5 35.6 35.7 35.8 35.9 Classes representing formulas. . . . . . . A spreadsheet that parses formulas. . . . . The evaluate method of trait Evaluator. A library for arithmetic operations. . . . . The nished spreadsheet component. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807 811 814 816 822

xxxiii

Cover Overview Contents Discuss Suggest Glossary Index

ForewordIm not sure where I rst came across the Scala language. Maybe on a forum for programming language enthusiasts such as Lambda the Ultimate, or maybe in more pedestrian quarters: Reddit, or the like. Although I was intrigued at rst blush, I owe my deeper exploration and enthusiasm for the language to two individuals: David Pollak, creator of the Lift web framework, and Steve Jenson, a former colleague at Twitter and generally brilliant programmer. Following David and Steve, I arrived to Scala in the late-middle stage of the languages history to date. By 2008, Scala had spent ve years evolving from its initial release, and had formed around it a tight-knit community of academics, tinkerers, and even a few consultants. The mailing lists were full of spirited debates, announcements of exciting libraries, and a general camaraderie and shared joy for seeing what this powerful new tool could do. What Scala lacked, at that point, was a collection of success stories around major production deployments. The decision to use Scala at Twitter, where I then worked, was not an easy one to make. Our infrastructure was buckling under the weight of extreme growth. Picking a relative unknown as our language of choice for building the high-performance distributed systems that would keep our edgling service alive was risky. Still, the benets that Scala offered were (and are) compelling, and our engineers were quickly able to produce prototypes that proved out the languages effectiveness. In the intervening time, Ive seen a heartening number of companies large and small adopting Scala. In that time, too, the question of Scalas complexity has been raised. From the outside, Scalas many features might appear to be a kind of complexity. To understand Scala, though, is to understand its goal of being a scalable language. You can be writing real-world code in Scala in an afternoon. As your understanding of the language and, indeed, Cover Overview Contents Discuss Suggest Glossary Index

Foreword of the art and science of programming as a whole expands, theres more of Scala there to wield to your advantage. Thats not complexity. Its exibility. To be clear: Scala will challenge you. Thats part of the joy of using it. You wont understand the full power of its type system by the end of your rst day. You wont understand the zen of objects being functions and functions being objects in your rst week. Each feature of the language is another light bulb waiting to switch on over your head. Im certain youll enjoy the experience of being gradually illuminated as you read this book and write code. Ive watched programmers learn Scala on the job and succeed. It can be done, and it can be fun. As Scala programmers like me have grown to better understand what this powerful language can do, so too has Scala evolved to meet programmers needs. Scala 2.8 smoothes out some rough spots in the collection libraries and adds useful features like named and default arguments to methods. While Scala has been a perfectly productive language to work with for some time, as of 2.8 it feels even more solid and polished. The new 2.8 release is icing on the cake. In my experience, Scala was ready for production deployments two years ago. Today, its even better, and I cant imagine building a new system without it. Presently, Im doing just that. For me, Scala has gone from being a risky gamble to a trusted tool in two short years. I look forward to taking advantage of the latest features in Scala 2.8, and to using this book as the denitive reference for it, direct from the creator of the language Ive grown to depend on. Alex Payne Portland, Oregon October 27, 2010

xxxv

Cover Overview Contents Discuss Suggest Glossary Index

Foreword to the First EditionMartin Odersky made a huge impact on the Java world with his design of the Pizza language. Although Pizza itself never became popular, it demonstrated that object-oriented and functional language features, when combined with skill and taste, form a natural and powerful combination. Pizzas design became the basis for generics in Java, and Martins GJ (Generic Java) compiler was Sun Microsystems standard compiler starting in 1.3 (though with generics disabled). I had the pleasure of maintaining this compiler for a number of years, so I can report from rst-hand experience that Martins skill in language design extends to language implementation. Since that time, we at Sun tried to simplify program development by extending the language with piecemeal solutions to particular problems, like the for-each loop, enums, and autoboxing. Meanwhile, Martin continued his work on more powerful orthogonal language primitives that allow programmers to provide solutions in libraries. Lately, there has been a backlash against statically typed languages. Experience with Java has shown that programming in a static language results in an abundance of boilerplate. The common wisdom is that one must abandon static typing to eliminate the boilerplate, and there is a rising interest in dynamic languages such as Python, Ruby, and Groovy. This common wisdom is debunked by the existence of Martins latest brainchild, Scala. Scala is a tastefully typed language: it is statically typed, but explicit types appear in just the right places. Scala takes powerful features from object-oriented and functional languages, and combines them with a few novel ideas in a beautifully coherent whole. The syntax is so lightweight, and its primitives so expressive, that APIs can be used with virtually no syntactic overhead at all. Examples can be found in standard libraries such as parser combinators and actors. In this sense Scala supports embedded domain-specic languages. Cover Overview Contents Discuss Suggest Glossary Index

Foreword to the First Edition Will Scala be the next great language? Only time will tell. Martin Oderskys 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 Gafter San Jose, California September 3, 2008

xxxvii

Cover Overview Contents Discuss Suggest Glossary Index

AcknowledgmentsMany people have contributed to this book and to the material it covers. We are grateful to all of them. Scala itself has been a collective effort of many people. The design and the implementation of version 1.0 was helped by Philippe Altherr, Vincent Cremet, Gilles Dubochet, Burak Emir, Stphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, and Matthias Zenger. Phil Bagwell, Antonio Cunei, Iulian Dragos, Gilles Dubochet, Miguel Garcia, Philipp Haller, Sean McDirmid, Ingo Maier, Donna Malayeri, Adriaan Moors, Hubert Plociniczak, Paul Phillips, Aleksandar Prokopec, Tiark Rompf, Lukas Rytz, and Geoffrey Washburn joined in the effort to develop the second and current version of the language and tools. Gilad Bracha, Nathan Bronson, Caoyuan, Aemon Cannon, Craig Chambers, Chris Conrad, Erik Ernst, Matthias Felleisen, Mark Harrah, Shriram Krishnamurti, Gary Leavens, David MacIver, Sebastian Maneth, Rickard Nilsson, Erik Meijer, Lalit Pant, David Pollak, Jon Pretty, Klaus Ostermann, Jorge Ortiz, Didier Rmy, Miles Sabin, Vijay Saraswat, Daniel Spiewak, James Strachan, Don Syme, Erik Torreborre, Mads Torgersen, Philip Wadler, Jamie Webb, John Williams, Kevin Wright, and Jason Zaugg have shaped the design of the language by graciously sharing their ideas with us in lively and inspiring discussions, by contributing important pieces of code to the open source effort, as well as through comments on previous versions of this document. The contributors to the Scala mailing list have also given very useful feedback that helped us improve the language and its tools. George Berger has worked tremendously to make the build process and the web presence for the book work smoothly. As a result this project has been 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, Cover Overview Contents Discuss Suggest Glossary Index

Acknowledgments William Cook, Bruce Eckel, Stphane Micheloud, Todd Millstein, David Pollak, Frank Sommers, Philip Wadler, and Matthias Zenger. Thanks also to the 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, Tao Ma, Jeffery Miller, Suresh Pai, Russ Rufer, Dave W. Smith, Scott Turnquest, Walter Vannini, Darlene Wallach, and Jonathan Andrew Wolter. And wed like to thank Dewayne Johnson and Kim Leedy for their help with the cover art, and Frank Sommers for his work on the index. Wed also like to extend a special thanks to all of our readers who contributed comments. Your comments were very helpful to us in shaping this into an even better book. We couldnt print the names of everyone who contributed comments, but here are the names of readers who submitted at least ve comments during the eBook PrePrint stage by clicking on the Suggest link, sorted rst by the highest total number of comments submitted, then alphabetically. Thanks goes to: David Biesack, Donn Stephan, Mats Henricson, Rob Dickens, Blair Zajac, Tony Sloane, Nigel Harrison, Javier Diaz Soto, William Heelan, Justin Forder, Gregor Purdy, Colin Perkins, Bjarte S. Karlsen, Ervin Varga, Eric Willigers, Mark Hayes, Martin Elwin, Calum MacLean, Jonathan Wolter, Les Pruszynski, Seth Tisue, Andrei Formiga, Dmitry Grigoriev, George Berger, Howard Lovatt, John P. Eurich, Marius Scurtescu, Jeff Ervin, Jamie Webb, Kurt Zoglmann, Dean Wampler, Nikolaj Lindberg, Peter McLain, Arkadiusz Stryjski, Shanky Surana, Craig Bordelon, Alexandre Patry, Filip Moens, Fred Janon, Jeff Heon, Boris Lorbeer, Jim Menard, Tim Azzopardi, Thomas Jung, Walter Chang, Jeroen Dijkmeijer, Casey Bowman, Martin Smith, Richard Dallaway, Antony Stubbs, Lars Westergren, Maarten Hazewinkel, Matt Russell, Remigiusz Michalowski, Andrew Tolopko, Curtis Stanford, Joshua Cough, Zemian Deng, Christopher Rodrigues Macias, Juan Miguel Garcia Lopez, Michel Schinz, Peter Moore, Randolph Kahle, Vladimir Kelman, Daniel Gronau, Dirk Detering, Hiroaki Nakamura, Ole Hougaard, Bhaskar Maddala, David Bernard, Derek Mahar, George Kollias, Kristian Nordal, Normen Mueller, Rafael Ferreira, Binil Thomas, John Nilsson, Jorge Ortiz, Marcus Schulte, Vadim Gerassimov, Cameron Taggart, Jon-Anders Teigen, Silvestre Zabala, Will McQueen, and Sam Owen. We would also like to think those who submitted comments and errata after the rst edition was published, including Felix Siegrist, Lothar MeyerLerbs, Diethard Michaelis, Roshan Dawrani, Donn Stephan, William Uther, Cover Overview Contents Discuss Suggest Glossary Index

xxxix

Acknowledgments Francisco Reverbel, Jim Balter, and Freek de Bruijn. Lex would like to thank Aaron Abrams, Jason Adams, Henry and Emily Crutcher, Joey Gibson, Gunnar Hillert, Matthew Link, Toby Reyelts, Jason Snape, John and Melinda Weathers, and all of the Atlanta Scala Enthusiasts for many helpful discussions about the language design, its mathematical underpinnings, and how to present Scala to working engineers. Lastly, Bill would also like to thank Gary Cornell, Greg Doench, Andy Hunt, Mike Leonard, Tyler Ortman, Bill Pollock, Dave Thomas, and Adam Wright for providing insight and advice on book publishing.

xl

Cover Overview Contents Discuss Suggest Glossary Index

IntroductionThis book is a tutorial for the Scala programming language, written by people directly involved in the development of Scala. Our goal is that by reading this book, you can learn everything you need to be a productive Scala programmer. All examples in this book compile with Scala version 2.8.1.

Who should read this bookThe main target audience for this book is programmers who want to learn to 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 to programmers wishing to expand their horizons by learning new concepts. If youre a Java programmer, for example, reading this book will expose you to many concepts from functional programming as well as advanced objectoriented ideas. We believe learning about Scala, and the ideas behind it, can help you become a better programmer in general. General programming knowledge is assumed. While Scala is a ne rst programming language, this is not the book to use to learn programming. On the other hand, no specic knowledge of programming languages is required. Even though most people use Scala on the Java platform, this book does not presume you know anything about Java. However, we expect many readers to be familiar with Java, and so we sometimes compare Scala to Java to help such readers understand the differences.

How to use this bookBecause the main purpose of this book is to serve as a tutorial, the recommended way to read this book is in chapter order, from front to back. We have tried hard to introduce one topic at a time, and explain new topics only Cover Overview Contents Discuss Suggest Glossary Index

Introduction in terms of topics weve already introduced. Thus, if you skip to the back to get an early peek at something, you may nd it explained in terms of concepts you dont quite understand. To the extent you read the chapters in order, we think youll nd it quite straightforward to gain competency in Scala, one step at a time. If you see a term you do not know, be sure to check the glossary and the index. Many readers will skim parts of the book, and that is just ne. The glossary and index can help you backtrack whenever you skim over something too quickly. After you have read the book once, it should also serve as a language reference. There is a formal specication of the Scala language, but the language specication tries for precision at the expense of readability. Although this book doesnt cover every detail of Scala, it is quite comprehensive and should serve as an approachable language reference as you become more adept at programming in Scala.

xlii

How to learn ScalaYou will learn a lot about Scala simply by reading this book from cover to cover. You can learn Scala faster and more thoroughly, though, if you do a few extra things. First of all, you can take advantage of the many program examples included in the book. Typing them in yourself is a way to force your mind through each line of code. Trying variations is a way to make them more fun and to make sure you really understand how they work. Second, keep in touch with the numerous online forums. That way, you and other Scala enthusiasts can help each other. There are numerous mailing lists, discussion forums, a chat room, a wiki, and multiple Scala-specic article feeds. Take some time to nd ones that t your information needs. You will spend a lot less time stuck on little problems, so you can spend your time on deeper, more important questions. Finally, once you have read enough, take on a programming project of your own. Work on a small program from scratch, or develop an add-in to a larger program. You can only go so far by reading.

Cover Overview Contents Discuss Suggest Glossary Index

Introduction

xliii

EBook featuresThis book is available in both paper and PDF eBook form. The eBook is not simply an electronic copy of the paper version of the book. While the content is the same as in the paper version, the eBook has been carefully designed and optimized for reading on a computer screen. The rst thing to notice is that most references within the eBook are hyperlinked. If you select a reference to a chapter, gure, or glossary entry, your PDF viewer should take you immediately to the selected item so that you do not have to ip around to nd it. Additionally, at the bottom of each page in the eBook are a number of navigation links. The Cover, Overview, and Contents links take you to the front matter of the book. The Glossary and Index links take you to reference parts of the book. Finally, the Discuss link takes you to an online forum where you discuss questions with other readers, the authors, and the larger Scala community. If you nd a typo, or something you think could be explained better, please click on the Suggest link, which will take you to an online web application where you can give the authors feedback. Although the same pages appear in the eBook as the printed book, blank pages are removed and the remaining pages renumbered. The pages are numbered differently so that it is easier for you to determine PDF page numbers when printing only a portion of the eBook. The pages in the eBook are, therefore, numbered exactly as your PDF viewer will number them.

Typographic conventionsThe rst time a term is used, it is italicized. Small code examples, such as x + 1, are written inline with a mono-spaced font. Larger code examples are put into mono-spaced quotation blocks like this:def hello() { println("Hello, world!") }

When interactive shells are shown, responses from the shell are shown in a lighter font:scala> 3 + 4 res0: Int = 7

Cover Overview Contents Discuss Suggest Glossary Index

Introduction

xliv

Content overview Chapter 1, A Scalable Language, gives an overview of Scalas design as well as the reasoning, and history, behind it. Chapter 2, First Steps in Scala, shows you how to do a number of basic programming tasks in Scala, without going into great detail about how they work. The goal of this chapter is to get your ngers started typing and running Scala code. Chapter 3, Next Steps in Scala, shows you several more basic programming tasks that will help you get up to speed quickly in Scala. After completing this chapter, you should be able to start using Scala for simple scripting tasks. Chapter 4, Classes and Objects, starts the in-depth coverage of Scala with a description of its basic object-oriented building blocks and instructions on how to compile and run a Scala application. Chapter 5, Basic Types and Operations, covers Scalas basic types, their literals, the operations you can perform on them, how precedence and associativity works, and what rich wrappers are. Chapter 6, Functional Objects, dives more deeply into the objectoriented features of Scala, using functional (i.e., immutable) rational numbers as an example. Chapter 7, Built-in Control Structures, shows you how to use Scalas built-in control structures: if, while, for, try, and match. Chapter 8, Functions and Closures, provides in-depth coverage of functions, the basic building block of functional languages. Chapter 9, Control Abstraction, shows how to augment Scalas basic control structures by dening your own control abstractions. Chapter 10, Composition and Inheritance, discusses more of Scalas support for object-oriented programming. The topics are not as fundamental as those in Chapter 4, but they frequently arise in practice. Chapter 11, Scalas Hierarchy, explains Scalas inheritance hierarchy and discusses its universal methods and bottom types. Cover Overview Contents Discuss Suggest Glossary Index

Introduction Chapter 12, Traits, covers Scalas mechanism for mixin composition. The chapter shows how traits work, describes common uses, and explains how traits improve on traditional multiple inheritance. Chapter 13, Packages and Imports, discusses issues with programming in the large, including top-level packages, import statements, and access control modiers like protected and private. Chapter 14, Assertions and Unit Testing, shows Scalas assertion mechanism and gives a tour of the various tools available for writing tests in Scala. Chapter 15, Case Classes and Pattern Matching, introduces twin constructs that support you when writing regular, non-encapsulated data structures. Case classes and pattern matching are particularly helpful for tree-like recursive data. Chapter 16, Working with Lists, explains in detail lists, which are probably the most commonly used data structure in Scala programs. Chapter 17, Collections, shows you how to use the basic Scala collections, 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 concludes with a case study on discrete event simulation, which shows some stateful objects in action. Chapter 19, Type Parameterization, explains some of the techniques for information hiding introduced in Chapter 13 by means of a concrete example: the design of a class for purely functional queues. The chapter builds up to a description of variance of type parameters and how it interacts with information hiding. Chapter 20, Abstract Members, describes all kinds of abstract members that Scala supports. Not only methods, but also elds and types can be declared abstract. Chapter 21, Implicit Conversions and Parameters, covers two constructs that can help you omit tedious details from source code, letting the compiler supply them instead. Cover Overview Contents Discuss Suggest Glossary Index

xlv

Introduction Chapter 22, Implementing Lists, describes the implementation of class List. It is important to understand how lists work in Scala, and furthermore the implementation demonstrates the use of several of Scalas features. Chapter 23, For Expressions Revisited, shows how for expressions are translated to invocations of map, flatMap, filter, and foreach. Chapter 24, The Scala Collections API, gives a detailed tour of the collections library. Chapter 25, The Architecture of Scala Collections, shows how the collection library is built and how you can implement your own collections. Chapter 26, Extractors, shows how to pattern match against arbitrary classes, not just case classes. Chapter 27, Annotations, shows how to work with language extension via annotation. The chapter describes several standard annotations and shows you how to make your own. Chapter 28, Working with XML, explains how to process XML in Scala. The chapter shows you idioms for generating XML, parsing it, and processing it once it is parsed. Chapter 29, Objects As Modules, shows how Scalas objects are rich enough to remove the need for a separate modules system. Chapter 30, Object Equality, points out several issues to consider when writing an equals method. There are several pitfalls to avoid. Chapter 31, Combining Scala and Java, discusses issues that arise when combining Scala and Java together in the same project, and suggests ways to deal with them. Chapter 32, Actors and Concurrency, shows you how to use Scalas actors concurrency library. Although you can use the Java Platforms concurrency primitives and libraries from Scala programs, actors can help you avoid the deadlocks and race conditions that plague the traditional threads and locks approach to concurrency. Cover Overview Contents Discuss Suggest Glossary Index

xlvi

Introduction Chapter 33, Combinator Parsing, shows how to build parsers using Scalas library of parser combinators. Chapter 34, GUI Programming, gives a quick tour of a Scala library that simplies GUI programming with Swing. Chapter 35, The SCells Spreadsheet, ties everything together by showing a complete spreadsheet application written in Scala.

xlvii

ResourcesAt http://www.scala-lang.org, the main website for Scala, youll nd the latest Scala release and links to documentation and community resources. For a more condensed page of links to Scala resources, visit this books website: http://booksites.artima.com/programming_in_scala_2ed. To interact with other readers of this book, check out the Programming in Scala Forum, at: http://www.artima.com/forums/forum.jsp?forum=282.

Source codeYou can download a ZIP le containing the source code of this book, which is released under the Apache 2.0 open source license, from the books website: http://booksites.artima.com/programming_in_scala_2ed.

ErrataAlthough this book has been heavily reviewed and checked, errors will inevitably slip through. For a (hopefully short) list of errata for this book, visit http://booksites.artima.com/programming_in_scala_2ed/errata. If you nd an error, please report it at the above URL, so that we can be sure to x it in a future printing or edition of this book.

Cover Overview Contents Discuss Suggest Glossary Index

Programming in ScalaSecond Editionprintln("Hello, reader!")

Cover Overview Contents Discuss Suggest Glossary Index

Chapter 1

A Scalable LanguageThe name Scala stands for scalable language. The language is so named because it was designed to grow with the demands of its users. You can apply Scala to a wide range of programming tasks, from writing small scripts to building large systems.1 Scala is easy to get into. It runs on the standard Java platform and interoperates seamlessly with all Java libraries. Its quite a good language for writing scripts that pull together Java components. But it can apply its strengths even more when used for building large systems and frameworks of reusable components. Technically, Scala is a blend of object-oriented and functional programming concepts in a statically typed language. The fusion of object-oriented and functional programming shows up in many different aspects of Scala; it is probably more pervasive than in any other widely used language. The two programming styles have complementary strengths when it comes to scalability. Scalas functional programming constructs make it easy to build interesting things quickly from simple parts. Its object-oriented constructs make 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 new kinds of programming patterns and component abstractions. It also leads to a 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 highlevel view of Scalas design and the reasoning behind it. After reading the chapter you should have a basic feel for what Scala is and what kinds of1 Scala

is pronounced skah-lah.

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language

50

tasks it might help you accomplish. Although this book is a Scala tutorial, this chapter isnt really part of the tutorial. If youre eager to start writing some 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, modies the map by adding a new binding ("Japan" -> "Tokyo"), and prints the capital associated with the country France.2 The notation in this example is high-level, to the point, and not cluttered with extraneous semicolons or type annotations. Indeed, the feel is that of a modern scripting language like Perl, Python, or Ruby. One common characteristic of these languages, which is relevant for the example above, is that they each support an associative map construct in the syntax of the language. Associative maps are very useful because they help keep programs legible and concise. However, sometimes you might not agree with their one size ts all philosophy, because you need to control the properties of the maps you use in your program in a more ne-grained way. Scala gives you this ne-grained control if you need it, because maps in Scala are not language syntax. They are library abstractions that you can extend and adapt. In the above program, youll get a default Map implementation, but you can easily change that. You could for example specify a particular implementation, such as a HashMap or a TreeMap, or you could specify that the map should be thread-safe, by mixing in a SynchronizedMap trait. You could specify a default value for the map, or you could override any other method of the map you create. In each case, you can use the same easy access syntax for maps as in the example above.2 Please bear with us if you dont understand all details of this program. They will be explained in the next two chapters.

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language

51

This example shows that Scala can give you both convenience and exibility. Scala has a set of convenient constructs that help you get started quickly 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 always tailor the program to your requirements, because everything is based on library modules that you can select and adapt as needed. Growing new types Eric Raymond introduced the cathedral and bazaar as two metaphors of software development.3 The cathedral is a near-perfect building that takes a long time to build. Once built, it stays unchanged for a long time. The bazaar, by contrast, is adapted and extended each day by the people working in it. In Raymonds work the bazaar is a metaphor for open-source software development. Guy Steele noted in a talk on growing a language that the same distinction can be applied to language design.4 Scala is much more like a bazaar than a cathedral, in the sense that it is designed to be extended and adapted by the people programming in it. Instead of providing all constructs you might ever need in one perfectly complete language, Scala puts the tools for building such constructs into your hands. Heres an example. Many applications need a type of integer that can become arbitrarily large without overow or wrap-around of arithmetic operations. Scala denes such a type in library class scala.BigInt. Here is the denition of a method using that type, which calculates the factorial of a passed integer value:5def 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 and operators such as * and - with values of that type. Yet it is just a class thatThe Cathedral and the Bazaar. [Ray99] Growing a language. [Ste99] 5 factorial(x), or x! in mathematical notation, is the result of computing 1 * 2 * ... * x, with 0! dened to be 1.4 Steele, 3 Raymond,

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language

52

happens to be dened in Scalas standard library.6 If the class were missing, it would be straightforward for any Scala programmer to write an implementation, for instance, by wrapping Javas class java.math.BigInteger (in fact thats how Scalas BigInt class is implemented). Of course, you could also use Javas class directly. But the result is not nearly as pleasant, because although Java allows you to create new types, those types dont 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 typesbig decimals,

complex numbers, rational numbers, condence intervals, polynomialsthe list goes on. Some programming languages implement some of these types natively. For instance, Lisp, Haskell, and Python implement big integers; Fortran and Python implement complex numbers. But any language that attempted to implement all of these abstractions at the same time would simply become too big to be manageable. Whats more, even if such a language were to exist, some applications would surely benet from other numberlike types that were not supplied. So the approach of attempting to provide everything in one language doesnt scale very well. Instead, Scala allows users to grow and adapt the language in the directions they need by dening easy-to-use libraries that feel like native language support. Growing new control constructs The previous example demonstrates that Scala lets you add new types that can be used as conveniently as built-in types. The same extension principle also applies to control structures. This kind of extensibility is illustrated by Scalas API for actor-based concurrent programming.comes with a standard library, some of which will be covered in this book. For more information, you can also consult the librarys Scaladoc documentation, which is available in the distribution and online at http://www.scala-lang.org.6 Scala

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language

53

As multicore processors proliferate in the coming years, achieving acceptable performance may increasingly require that you exploit more parallelism in your applications. Often, this will mean rewriting your code so that computations are distributed over several concurrent threads. Unfortunately, creating dependable multi-threaded applications has proven challenging in practice. Javas threading model is built around shared memory and locking, a model that is often difcult to reason about, especially as systems scale up in size and complexity. It is hard to be sure you dont have a race condition or deadlock lurkingsomething that didnt show up during testing, but might just show up in production. An arguably safer alternative is a message passing architecture such as the actors approach used by the Erlang programming language. Java comes with a rich, thread-based concurrency library. Scala programs can use it like any other Java API. However, Scala also offers an