Programming Scala introduces an exciting new language that offers all the benefits of a modern object model, functional programming, and an advanced type system. Packed with code examples, this comprehensive book teaches you how to be productive with Scala quickly, and explains what makes this language ideal for today’s scalable, distributed, component-based applications that support concurrency and distribution. You’ll also learn how Scala takes advantage of the advanced Java Virtual Machine as a platform for programming languages.
Learn more at programmingscala.com or at the book’s catalog page (http://oreilly.com/catalog/9780596155957/).
Welcome to Programming Scala
Programming languages become popular for many reasons. Sometimes, programmers on a given platform prefer a particular language, or one is institutionalized by a vendor. Most Mac OS programmers use Objective-C. Most Windows programmers use C++ and .NET languages. Most embedded-systems developers use C and C++.
Sometimes, popularity derived from technical merit gives way to fashion and fanaticism. C++, Java, and Ruby have been the objects of fanatical devotion amongst programmers.
Sometimes, a language becomes popular because it fits the needs of its era. Java was initially seen as a perfect fit for browser-based, rich client applications. Smalltalk captured the essence of Object-Oriented Programming (OOP) as that model of programming entered the mainstream.
Today, concurrency, heterogeneity, always-on services, and ever-shrinking development schedules are driving interest in Functional Programming (FP). It appears that the dominance of Object-Oriented Programming may be over. Mixing paradigms is becoming popular, even necessary.
We gravitated to Scala from other languages because Scala embodies many of the optimal qualities we want in a general-purpose programming language for the kinds of applications we build today: reliable, high performance, highly concurrent Internet and enterprise applications.
Scala is a multi-paradigm language, supporting both Object-Oriented and Functional Programming approaches. Scala is scalable, suitable for everything from short scripts up to large-scale, component-based applications. Scala is sophisticated, incorporating state-of-the art ideas from the halls of Computer Science departments worldwide. Yet, Scala is practical. Its creator, Martin Odersky, participated in the development of Java for years and understands the needs of professional developers.
Both of us were seduced by Scala, by its concise, elegant, and expressive syntax and by the breadth of tools it put at our disposal. In this book, we strive to demonstrate why all these qualities make Scala a compelling and indispensable programming language.
If you are an experienced developer who wants a fast, thorough introduction to Scala, then this book is for you. You may be evaluating Scala as a replacement or complement for your current languages. Maybe you have already decided to use Scala and you need to learn its features and how to use it well. Either way, we hope to illuminate this powerful language for you in an accessible way.
We assume that you are well versed in Object-Oriented Programming, but we don’t assume that you have prior exposure to Functional Programming. We assume you are experienced in one or more other programming languages. We draw parallels to features in Java, C#, Ruby, and other languages. If you know any of these languages, we’ll point out similar features in Scala, as well as many features that are new.
Whether you come from an Object-Oriented or Functional Programming background, you will see how Scala elegantly combines both paradigms, demonstrating their complementary nature. Using many examples, you will understand how and when to apply OOP and FP techniques to many different design problems.
In the end, we hope that you too will be seduced by Scala. Even if Scala does not end up becoming your day-to-day language, we hope you will gain insights that you can apply regardless of what language you are using.
Conventions Used in This Book
The following typographical conventions are used in this book:
- Indicates new terms, URLs, email addresses, filenames, and file extensions. Many italicized terms are defined in the Glossary.
- Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.
Constant width bold
- Shows commands or other text that should be typed literally by the user.
Constant width italic
- Shows text that should be replaced with user-supplied values or by values determined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming Scala by Dean Wampler and Alex Payne. Copyright 2009 O’Reilly Media, Inc., 978-0-596-15595-7.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at firstname.lastname@example.org.
Getting the Code Examples
You can download the code examples from http://examples.oreilly.com/9780596155964/. Unzip the files to a convenient location. See the
README.txt file in the distribution for instructions on building and using the examples.
Some of the example files can be run as scripts using the
scala command. Others must be compiled into class files. Some files contain deliberate errors and won’t compile. We have adopted a file naming convention to indicate each of these cases, although as you learn Scala it should become obvious from the contents of the files, in most cases.
Files that end in
-script.scalacan be run on a command line using
scala foo-script.scala. You can also start
scalain the interpreter mode (when you don’t specify a script file) and load any script file in the interpreter using the
Files that end in
-wont-compile.scalacontain deliberate errors that will cause them to fail to compile. We use this naming convention, along with one or more embedded comments about the errors, so it will be clear that they are invalid. Also, these files are skipped by the build process for the examples.
sake.scalaare used by our build tool, called
README.txtfile describes this tool.
All other Scala files must be compiled using
scalac. In the distribution, they are used either by other compiled or script files, such as tests, not all of which are listed in the book.
Safari® Books Online
When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://safari.oreilly.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707 829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:
To comment or ask technical questions about this book, send email to:
For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our web site at:
As we developed the book, many people read early drafts and suggested numerous improvements to the text, for which we are eternally grateful. We are especially grateful to Steve Jensen, Ramnivas Laddad, Marcel Molina, Bill Venners, and Jonas Bonér, for their extensive feedback.
Much of the feedback we received came through the Safari Rough Cuts releases and the online edition available at http://programmingscala.com. We are grateful for the feedback provided by (in no particular order) Iulian Dragos, Nikolaj Lindberg, Matt Hellige, David Vydra, Ricky Clarkson, Alex Cruise, Josh Cronemeyer, Tyler Jennings, Alan Supynuk, Tony Hillerson, Roger Vaughn, Arbi Sookazian, Bruce Leidl, Daniel Sobral, Eder Andres Avila, Marek Kubica, Henrik Huttunen, Bhaskar Maddala, Ged Byrne, Derek Mahar, Geoffrey Wiseman, Peter Rawsthorne, Geoffrey Wiseman, Joe Bowbeer, Alexander Battisti, Rob Dickens, Tim MacEachern, Jason Harris, Steven Grady, Bob Follek, Ariel Ortiz, Parth Malwankar, Reid Hochstedler, Jason Zaugg, Jon Hanson, Mario Gleichmann, David Gates, Zef Hemel, Michael Yee, Marius Kreis, Martin Süsskraut, Javier Vegas, Tobias Hauth, Francesco Bochicchio, Stephen Duncan Jr., Patrik Dudits, Jan Niehusmann, Bill Burdick, David Holbrook, Shalom Deitch, Jesper Nordenberg, Esa Laine, Gleb Frank, Simon Andersson, Patrik Dudits, Chris Lewis, Julian Howarth, Dirk Kuzemczak, Henri Gerrits, John Heintz, Stuart Roebuck, and Jungho Kim. Many other readers for whom we only have
'user names' also provided feedback. We wish to thank Zack, JoshG, ewilligers, abcoates, brad, teto, pjcj, mkleint, dandoyon, Arek, rue, acangiano, vkelman, bryanl, Jeff, mbaxter, pjb3, kxen, hipertracker, ctran, Ram R., cody, Nolan, Joshua, Ajay, Joe, and anonymous contributers. We apologize if we have overlooked anyone!
Our editor, Mike Loukides, knows how to push and prod gentle. He’s been a great help throughout this crazy process. Many other people at O’Reilly were always there to answer our questions and help us move forward.
We thank Jonas Bonér for writing the Forward for the book. Jonas is a longtime friend and collaborator from the Aspect-Oriented Programming (AOP) community. For years, he has done pioneering work in the Java community. Now, he is applying his energies to promoting Scala and growing that community.
Bill Venners graciously provided the quote on the back cover. The first published book on Scala, Programming in Scala, that he co-wrote with Martin Odersky and Lex Spoon, is indispensable for the Scala developer. Bill has also created the wonderful ScalaTest library.
We have learned a lot from fellow developers around the world. Besides Jonas and Bill, Debasish Ghosh, James Iry, Daniel Spiewak, David Pollack, Paul Snively, Ola Bini, Daniel Sobral, Josh Suereth, Robey Pointer, Nathan Hamblen, Jorge Ortiz, and others have illuminated dark corners with their blog entries, forum discussions, and personal conversations.
Dean thanks his colleagues at Object Mentor and several developers at client sites for many stimulating discussions on languages, software design, and the pragmatic issues facing developers in industry. The members of the Chicago Area Scala Enthusiasts (CASE) group have also been a source of valuable feedback and inspiration.
Alex dedicates his portion of the book to his mother, who bestowed upon him an appreciation for good writing and the accompanying intellectual tools with which to attempt to produce it. Alex thanks his lovely partner, Kristen, for her patience and kindness throughout the writing process. He would also like to thank his colleagues at Twitter for their encouragement and superb work in demonstrating Scala’s effectiveness.
Most of all, we thank Martin Odersky and his team for creating Scala.