Praise for the earlier editions of Programming in Scala Programming in Scala is probably one of the best programming books I've ever read. I like the writing style, the brevity, and the thorough explanations. The book seems to answer every question as it enters my mind—it's always one step ahead of me. The authors don't just give you some code and take things for granted. They give you the meat so you really understand what's 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 efficiently. This book is great for any programmer who is trying to wrap their head around the flexibility 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 flows 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 find out more about the Scala language. - Matthew Todd 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 find 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 it's also an excellent reference. I'd say that it occupies a prominent place on my bookshelf, except that I'm 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 book's pragmatic approach in introducing the power of combining object-oriented 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. There's always a fine line to walk in a language introduction book between giving too much or not enough information. I find Programming in Scala to achieve a perfect balance. - Jeff Heon, Programmer Analyst 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 don't know why more authors don't use this feature, because it's 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 isn't 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 you're reading the electronic version, definitely 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 well-written 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. The book Programming in Scala outright oozes the huge amount of hard work that has gone into it. I've 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 hasn't 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 sufficiently 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 Loeffler, 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. You'll find everything here you need to learn this promising language. - Christian Neukirchen Programming in Scala, Third Edition Programming in Scala, Third Edition Third Edition Martin Odersky, Lex Spoon, Bill Venners Artima Press Walnut Creek, California Programming in Scala Third 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-2016 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 Third edition published as PrePrint® eBook 2016 Third edition published 2016 Build date of this impression April 08, 2016 Produced in the United States of America No part of this publication may be reproduced, modified, 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. to Nastaran - M.O. to Fay - L.S. to Siew - B.V. Table of Contents Table of Contents Foreword 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. Scala's Hierarchy 12. Traits 13. Packages and Imports 14. Assertions and Tests 15. Case Classes and Pattern Matching 16. Working with Lists 17. Working with Other Collections 18. Mutable Objects 19. Type Parameterization 20. Abstract Members 21. Implicit Conversions and Parameters 22. Implementing Lists 23. For Expressions Revisited 24. Collections in Depth 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. Futures and Concurrency 33. Combinator Parsing 34. GUI Programming 35. The SCells Spreadsheet A. Scala Scripts on Unix and Windows Glossary Bibliography About the Authors Index Foreword You've chosen a great time to pick up this book! Scala adoption keeps accelerating, our community is thriving, and job ads abound. Whether you're programming for fun or profit (or both), Scala's promise of joy and productivity is proving hard to resist. To me, the true joy of programming comes from tackling interesting challenges with simple, sophisticated solutions. Scala's mission is not just to make this possible, but enjoyable, and this book will show you how. I first experimented with Scala 2.5, and was immediately drawn to its syntactic and conceptual regularity. When I ran into the irregularity that type parameters couldn't have type parameters themselves, I (timidly) walked up to Martin Odersky at a conference in 2006 and proposed an internship to remove that restriction. My contribution was accepted, bringing support for type constructor polymorphism to Scala 2.7 and up. Since then, I've worked on most other parts of the compiler. In 2012 I went from post-doc in Martin's lab to Scala team lead at Typesafe, as Scala, with version 2.10, graduated from its pragmatic academic roots to a robust language for the enterprise. Scala 2.10 was a turning point from fast-paced, feature-rich releases based on academic research, towards a focus on simplification and increased adoption in the enterprise. We shifted our attention to issues that won't be written up in dissertations, such as binary compatibility between major releases. To balance stability with our desire to keep evolving and refining the Scala platform, we're working towards a smaller core library, which we aim to stabilize while evolving the platform as a whole. To enable this, my first project as Scala tech lead was to begin modularizing the Scala standard library in 2.11. To reduce the rate of change, Typesafe also decided to alternate changing the library and the compiler. This edition of Programming in Scala covers Scala 2.12, which will be a compiler release sporting a new back-end and optimizer to make the most of Java 8's new features. For interoperability with Java and to enjoy the same benefits from JVM optimizations, Scala compiles functions to the same bytecode as the Java 8 compiler. Similarly, Scala traits now compile to Java interfaces with default methods. Both compilation schemes reduce the magic that older Scala compilers had to perform, aligning us more closely with the Java platform, while improving both compile-time and run-time performance, with a smoother binary compatibility story to boot! These improvement to the Java 8 platform are very exciting for Scala, and it's very rewarding to see Java align with the trend Scala has been setting for over a decade! There's no doubt that Scala provides a much better functional programming experience, with immutability by default, a uniform treatment of expressions (there's hardly a return statement in sight in this book), pattern matching, definition-site variance (Java's use-site variance make function subtyping quite awkward), and so on! To be blunt, there's more to functional programming than nice syntax for lambdas. As stewards of the language, our goal is to develop the core language as much as to foster the ecosystem. Scala is successful because of the many excellent libraries, outstanding IDEs and tools, and the friendly and ever helpful members of our community. I've thoroughly enjoyed my first decade of Scala—as an implementer of the language, it's such a thrill and inspiration to meet programmers having fun with Scala across so many domains. I love programming in Scala, and I hope you will too. On behalf of the Scala community, welcome! Adriaan Moors San Francisco, CA January 14, 2016 Acknowledgments Many 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, Stéphane 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 Rémy, 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, William Cook, Bruce Eckel, Stéphane 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 we'd like to thank Dewayne Johnson and Kim Leedy for their help with the cover art, and Frank Sommers for his work on the index. We'd 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 couldn't print the names of everyone who contributed comments, but here are the names of readers who submitted at least five comments during the eBook PrePrint® stage by clicking on the Suggest link, sorted first 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,