Instant Download Programming in Scala Updated For Scala 2 12 3rd Edition Martin Odersky PDF All Chapters
Instant Download Programming in Scala Updated For Scala 2 12 3rd Edition Martin Odersky PDF All Chapters
com
https://textbookfull.com/product/programming-in-
scala-updated-for-scala-2-12-3rd-edition-martin-
odersky/
https://textbookfull.com/product/programming-in-scala-fourth-
edition-1116-martin-odersky/
textbookfull.com
https://textbookfull.com/product/programming-scala-3rd-edition-dean-
wampler/
textbookfull.com
https://textbookfull.com/product/learning-concurrent-programming-in-
scala-prokopec/
textbookfull.com
https://textbookfull.com/product/going-big-a-scientists-guide-to-
large-projects-and-collaborations-1st-edition-christopher-w-stubbs/
textbookfull.com
Planning, Time, and Self-Governance: Essays in Practical
Rationality Michael E. Bratman
https://textbookfull.com/product/planning-time-and-self-governance-
essays-in-practical-rationality-michael-e-bratman/
textbookfull.com
https://textbookfull.com/product/behind-closed-doors-a-novel-lewis-
susan/
textbookfull.com
https://textbookfull.com/product/the-office-rival-1st-edition-kat-t-
masen/
textbookfull.com
https://textbookfull.com/product/bim-and-urban-land-
administration-1st-edition-abbas-rajabifard-author/
textbookfull.com
https://textbookfull.com/product/justice-and-natural-resources-an-
egalitarian-theory-first-edition-armstrong/
textbookfull.com
The Rough Guide to Poland 8th Edition Rough Guides
https://textbookfull.com/product/the-rough-guide-to-poland-8th-
edition-rough-guides/
textbookfull.com
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
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,
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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 thank those who submitted comments and errata after the first two editions were
published, including Felix Siegrist, Lothar Meyer-Lerbs, Diethard Michaelis, Roshan Dawrani, Donn
Stephan, William Uther, Francisco Reverbel, Jim Balter, and Freek de Bruijn, Ambrose Laing, Sekhar
Prabhala, Levon Saldamli, Andrew Bursavich, Hjalmar Peters, Thomas Fehr, Alain O'Dea, Rob
Dickens, Tim Taylor, Christian Sternagel, Michel Parisien, Joel Neely, Brian McKeon, Thomas Fehr,
Joseph Elliott, Gabriel da Silva Ribeiro, Thomas Fehr, Pablo Ripolles, Douglas Gaylor, Kevin Squire,
Harry-Anton Talvik, Christopher Simpkins, Martin Witmann-Funk, Jim Balter, Peter Foster, Craig
Bordelon, Heinz-Peter Gumm, Peter Chapin, Kevin Wright, Ananthan Srinivasan, Omar Kilani, Donn
Stephan, Guenther Waffler.
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.
A special thanks to Dave Briccetti and Adriaan Moors for reviewing the third edition, and to Marconi
Lanna for not only reviewing, but providing motivation for the third edition by giving a talk entitled
"What's new since Programming in Scala."
Bill would 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. Bill
would also like to thank Dick Wall for collaborating on Escalate'sStairway to Scala course, which is in
great part based on this book. Our many years of experience teaching Stairway to Scala has helped
make this book better. Lastly, Bill would like to thank Darlene Gruendl and Samantha Woolf for their
help in getting the third edition completed.
Introduction
This 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.11.7, except for
those marked 2.12, which compile with 2.12.0-M3.
EBOOK FEATURES
This 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 first thing to notice is that most references within the eBook are hyperlinked. If you select a
reference to a chapter, figure, or glossary entry, your PDF viewer should take you immediately to the
selected item so that you do not have to flip around to find 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 find 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 in 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 CONVENTIONS
The first 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
CONTENT OVERVIEW
• Chapter 1 "A Scalable Language," gives an overview of Scala's 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 fingers 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 Scala's 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 object-oriented features of Scala,
using functional (i.e., immutable) rational numbers as an example.
• Chapter 7 "Built-in Control Structures," shows you how to use Scala's 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 Scala's basic control structures by
defining your own control abstractions.
• Chapter 10 "Composition and Inheritance," discusses more of Scala's support for object-
oriented programming. The topics are not as fundamental as those in Chapter 4, but they
frequently arise in practice.
• Chapter 11 "Scala's Hierarchy," explains Scala's inheritance hierarchy and discusses its
universal methods and bottom types.
• Chapter 12 "Traits," covers Scala's 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 modifiers likeprotected and private.
• Chapter 14 "Assertions and Tests," shows Scala's assertion mechanism and gives a tour of
several tools available for writing tests in Scala, focusing on ScalaTest in particular.
• 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 "Working with Other Collections," shows you how to use the basic Scala
collections, such as lists, arrays, tuples, sets, and maps.
• Chapter 18 "Mutable Objects," explains mutable objects and the syntax Scala provides to
express them. The chapter concludes with a case study on discrete event simulation, which
shows some mutable 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 fields 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.
• 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 Scala's features.
• Chapter 23 "For Expressions Revisited," shows how for expressions are translated to
invocations of map, flatMap, filter, and foreach.
• Chapter 24 "Collections in Depth," 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 "Modular Programming Using Objects," shows how you can use Scala's objects as a
modules system.
• Chapter 30 "Object Equality," points out several issues to consider when writing
an equalsmethod. 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 "Futures and Concurrency," shows you how to use Scala's Future. Although you can
use the Java platform's concurrency primitives and libraries for Scala programs, futures can help
you avoid the deadlocks and race conditions that plague the traditional "threads and locks"
approach to concurrency.
• Chapter 33 "Combinator Parsing," shows how to build parsers using Scala's library of parser
combinators.
• Chapter 34 "GUI Programming," gives a quick tour of a Scala library that simplifies GUI
programming with Swing.
• Chapter 35 "The SCells Spreadsheet," ties everything together by showing a complete
spreadsheet application written in Scala.
RESOURCES
At http://www.scala-lang.org, the main website for Scala, you'll find the latest Scala release and links to
documentation and community resources. For a more condensed page of links to Scala resources, visit
this book's website:http://booksites.artima.com/programming_in_scala_3ed. 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 CODE
You can download a ZIP file containing the source code of this book, which is released under the
Apache 2.0 open source license, from the book's
website:http://booksites.artima.com/programming_in_scala_3ed.
ERRATA
Although 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_3ed/errata.
If you find an error, please report it at the above URL, so that we can fix it in a future printing or
edition of this book.
Programming in Scala, Third Edition
Third Edition
println("Hello, reader!")
Chapter 1
A Scalable Language
The 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. It's 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. Scala's 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 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 high-level view of Scala's design and
the reasoning behind it. After reading the chapter you should have a basic feel for what Scala is and
what kinds of tasks it might help you accomplish. Although this book is a Scala tutorial, this chapter
isn't really part of the tutorial. If you're eager to start writing some Scala code, you should jump ahead
to Chapter 2.
println(capital("France"))
This program sets up a map from countries to their capitals, modifies 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, but sometimes
you might not agree with their "one size fits all" philosophy because you need to control the properties
of the maps you use in your program in a more fine-grained way. Scala gives you this fine-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, you'll 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 invoke
the par method to obtain a ParMap that executes operations in parallel. 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.
This example shows that Scala can give you both convenience and flexibility. 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.
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 that happens to be defined in Scala's standard library.[6] If the
class were missing, it would be straightforward for any Scala programmer to write an implementation,
for instance, by wrapping Java's classjava.math.BigInteger (in fact that's how Scala's BigInt class is
implemented).
Of course, you could also use Java's class directly. But the result is not nearly as pleasant, because
although Java allows you to create new types, those types don't feel much like native language support:
import java.math.BigInteger
BigInt is representative of many other number-like types—big decimals, complex numbers, rational
numbers, confidence intervals, polynomials—the list goes on. Some programming languages
implement some of these types natively. For instance, Lisp, Haskell, and Pythonimplement 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.
What's more, even if such a language were to exist, some applications would surely benefit from other
number-like types that were not supplied. So the approach of attempting to provide everything in one
language doesn't scale very well. Instead, Scala allows users to grow and adapt the language in the
directions they need by defining easy-to-use libraries that feel like native language support.
A send is asynchronous; that is, the sending actor can proceed immediately, without waiting for the
message to be received and processed. Every actor has a mailbox in which incoming messages are
queued. An actor handles messages that have arrived in its mailbox via a receiveblock:
def receive = {
case Msg1 => ... // handle Msg1
case Msg2 => ... // handle Msg2
// ...
}
A receive block consists of a number of cases that each query the mailbox with a message pattern. The
first message in the mailbox that matches any of the cases is selected, and the corresponding action is
performed on it. Once the mailbox does not contain any messages, the actor suspends and waits for
further incoming messages.
As an example, here is a simple Akka actor implementing a checksum calculator service:
class ChecksumActor extends Actor {
var sum = 0
def receive = {
case Data(byte) => sum += byte
case GetChecksum(requester) =>
val checksum = ~(sum & 0xFF) + 1
requester ! checksum
}
}
This actor first defines a local variable named sum with initial value zero. It defines a receiveblock that
will handle messages. If it receives a Data message, it adds the contained byte to thesum variable. If it
receives a GetChecksum message, it calculates a checksum from the current value of sum and sends the
result back to the requester using the message send requester ! sum. The requester field is embedded in
the GetChecksum message; it usually refers to the actor that made the request.
We don't expect you to fully understand the actor example at this point. Rather, what's significant about
this example for the topic of scalability is that neither the receive block nor message send (!) are built-
in operations in Scala. Even though the receive block may look and act very much like a built-in
control construct, it is in fact a method defined in Akka's actors library. Likewise, even though `!' looks
like a built-in operator, it too is just a method defined in the Akka actors library. Both of these
constructs are completely independent of the Scala programming language.
The receive block and send (!) syntax look in Scala much like they look in Erlang, but in Erlang, these
constructs are built into the language. Akka also implements most of Erlang's other concurrent
programming constructs, such as monitoring failed actors and time-outs. All in all, the actor model has
turned out to be a very pleasant means for expressing concurrent and distributed computations. Even
though they must be defined in a library, actors can feel like an integral part of the Scala language.
This example illustrates that you can "grow" the Scala language in new directions even as specialized
as concurrent programming. To be sure, you need good architects and programmers to do this. But the
crucial thing is that it is feasible—you can design and implement abstractions in Scala that address
radically new application domains, yet still feel like native language support when used.
Scala is object-oriented
Object-oriented programming has been immensely successful. Starting from Simula in the mid-60s and
Smalltalk in the 70s, it is now available in more languages than not. In some domains, objects have
taken over completely. While there is not a precise definition of what object-oriented means, there is
clearly something about objects that appeals to programmers.
In principle, the motivation for object-oriented programming is very simple: all but the most trivial
programs need some sort of structure. The most straightforward way to do this is to put data and
operations into some form of containers. The great idea of object-oriented programming is to make
these containers fully general, so that they can contain operations as well as data, and that they are
themselves values that can be stored in other containers, or passed as parameters to operations. Such
containers are called objects. Alan Kay, the inventor of Smalltalk, remarked that in this way the
simplest object has the same construction principle as a full computer: it combines data with operations
under a formalized interface.[7] So objects have a lot to do with language scalability: the same
techniques apply to the construction of small as well as large programs.
Even though object-oriented programming has been mainstream for a long time, there are relatively
few languages that have followed Smalltalk in pushing this construction principle to its logical
conclusion. For instance, many languages admit values that are not objects, such as the primitive values
in Java. Or they allow static fields and methods that are not members of any object. These deviations
from the pure idea of object-oriented programming look quite harmless at first, but they have an
annoying tendency to complicate things and limit scalability.
By contrast, Scala is an object-oriented language in pure form: every value is an object and every
operation is a method call. For example, when you say 1 + 2 in Scala, you are actually invoking a
method named + defined in class Int. You can define methods with operator-like names that clients of
your API can then use in operator notation. This is how the designer of Akka's actors API enabled you
to use expressions such as requester ! sum shown in the previous example: `!' is a method of
the Actor class.
Scala is more advanced than most other languages when it comes to composing objects. An example is
Scala's traits. Traits are like interfaces in Java, but they can also have method implementations and
even fields.[8] Objects are constructed by mixin composition, which takes the members of a class and
adds the members of a number of traits to them. In this way, different aspects of classes can be
encapsulated in different traits. This looks a bit like multiple inheritance, but differs when it comes to
the details. Unlike a class, a trait can add some new functionality to an unspecified superclass. This
makes traits more "pluggable" than classes. In particular, it avoids the classical "diamond inheritance"
problems of multiple inheritance, which arise when the same class is inherited via several different
paths.
Scala is functional
In addition to being a pure object-oriented language, Scala is also a full-blown functional language.
The ideas of functional programming are older than (electronic) computers. Their foundation was laid
in Alonzo Church's lambda calculus, which he developed in the 1930s. The first functional
programming language was Lisp, which dates from the late 50s. Other popular functional languages are
Scheme, SML, Erlang, Haskell, OCaml, and F#. For a long time, functional programming has been a
bit on the sidelines—popular in academia, but not that widely used in industry. However, in recent
years, there has been an increased interest in functional programming languages and techniques.
Functional programming is guided by two main ideas. The first idea is that functions are first-class
values. In a functional language, a function is a value of the same status as, say, an integer or a string.
You can pass functions as arguments to other functions, return them as results from functions, or store
them in variables. You can also define a function inside another function, just as you can define an
integer value inside a function. And you can define functions without giving them a name, sprinkling
your code with function literals as easily as you might write integer literals like 42.
Functions that are first-class values provide a convenient means for abstracting over operations and
creating new control structures. This generalization of functions provides great expressiveness, which
often leads to very legible and concise programs. It also plays an important role for scalability. As an
example, the ScalaTest testing library offers an eventuallyconstruct that takes a function as an
argument. It is used like this:
val xs = 1 to 3
val it = xs.iterator
eventually { it.next() shouldBe 3 }
The code inside eventually—the assertion, it.next() shouldBe 3—is wrapped in a function that is passed
unexecuted to the eventually method. For a configured amount of time, eventually will repeatedly
execute the function until the assertion succeeds.
In most traditional languages, by contrast, functions are not values. Languages that do have function
values often relegate them to second-class status. For example, the function pointers of C and C++ do
not have the same status as non-functional values in those languages: Function pointers can only refer
to global functions, they do not allow you to define first-class nested functions that refer to some values
in their environment. Nor do they allow you to define unnamed function literals.
The second main idea of functional programming is that the operations of a program should map input
values to output values rather than change data in place. To see the difference, consider the
implementation of strings in Ruby and Java. In Ruby, a string is an array of characters. Characters in a
string can be changed individually. For instance you can change a semicolon character in a string to a
period inside the same string object. In Java and Scala, on the other hand, a string is a sequence of
characters in the mathematical sense. Replacing a character in a string using an expression
like s.replace(';', '.') yields a new string object, which is different from s. Another way of expressing this
is that strings are immutable in Java whereas they are mutable in Ruby. So looking at just strings, Java
is a functional language, whereas Ruby is not. Immutable data structures are one of the cornerstones of
functional programming. The Scala libraries define many more immutable data types on top of those
found in the Java APIs. For instance, Scala has immutable lists, tuples, maps, and sets.
Another way of stating this second idea of functional programming is that methods should not have
any side effects. They should communicate with their environment only by taking arguments and
returning results. For instance, the replace method in Java's String class fits this description. It takes a
string and two characters and yields a new string where all occurrences of one character are replaced by
the other. There is no other effect of callingreplace. Methods like replace are called referentially
transparent, which means that for any given input the method call could be replaced by its result
without affecting the program's semantics.
Functional languages encourage immutable data structures and referentially transparent methods. Some
functional languages even require them. Scala gives you a choice. When you want to, you can write in
an imperative style, which is what programming with mutable data and side effects is called. But Scala
generally makes it easy to avoid imperative constructs when you want because good functional
alternatives exist.
Scala is concise
Scala programs tend to be short. Scala programmers have reported reductions in number of lines of up
to a factor of ten compared to Java. These might be extreme cases. A more conservative estimate would
be that a typical Scala program should have about half the number of lines of the same program written
in Java. Fewer lines of code mean not only less typing, but also less effort at reading and understanding
programs and fewer possibilities of defects. There are several factors that contribute to this reduction in
lines of code.
First, Scala's syntax avoids some of the boilerplate that burdens Java programs. For instance,
semicolons are optional in Scala and are usually left out. There are also several other areas where
Scala's syntax is less noisy. As an example, compare how you write classes and constructors in Java
and Scala. In Java, a class with a constructor often looks like this:
// this is Java
Random documents with unrelated
content Scribd suggests to you:
graisseux, à travers un jour de cave, le grand-père gardait ses trois
petits-enfants en l'absence de la mère. De ses yeux sans regards, il
suivait leurs jeux de bêtes ; l'aîné, cinq ans, avait renversé son frère
hurlant, et à grands coups de pied dans le ventre, tentait de lui
arracher un trognon de pomme verte. Dans le lit, un mioche était en
train de s'étouffer, déjà violacé. Hélène relevait le traversin, séparait
les garnements, puis elle écouta les doléances du vieux : sa fille se
tuait à l'usine, tandis que lui croupissait, achevant de mourir. Sa voix
se cassa, tremblante ; il désignait les galopins immobiles… « Pas de
répit avec eux! Ils s'ingéniaient à le tourmenter. Tout à l'heure
encore, ils venaient de lui remplir ses sabots de terre. » Hélène
s'éloignait, revoyant la main noueuse avidement refermée sur
l'argent, dans la crainte d'une méchante farce des petits.
Elle prenait au plus court, pour rejoindre la berge. Jamais elle
n'avait été émue à ce point. Elle revit le pâle visage de Marthe Flénu,
évoqua les deux autres malheureuses rivées aux cylindres d'acier,
devant la rotation des bobines. Elles résumaient la somme des maux
qui accablent la femme ouvrière, lorsque l'homme disparu, infirme
ou indigne, laisse retomber sur elle le poids écrasant de la vie.
Comme elle passait devant l'usine, un groupe qui stationnait en face
se tut à son approche. A l'entrée de la vaste cour, André sortait
justement du bureau, en écoutant d'un air maussade le rapport d'un
vieux contremaître. Il aperçut Hélène :
— Tiens! qu'est-ce que tu fais là?
— Je rentrais. Que se passe-t-il?
— Rien, Dulac m'apprend que les bobineuses ne veulent pas
démordre de leur augmentation.
Et il eut un léger haussement d'épaules, tandis que Dulac, après
avoir soulevé sa casquette, se reculait avec un sourire qu'Hélène
jugea ironique. Le regard du vieux lui déplut aussi, trop direct, trop
admiratif. Elle avait de l'antipathie pour cet homme courtaud,
sanguin sous ses cheveux gris, dont les yeux quêteurs, la lippe
sensuelle justifiaient la mauvaise réputation. Toutes les filles le
redoutaient.
— Ah! voilà l'oncle, dit André, je te quitte.
A l'angle du bâtiment, Marcel Dugast, suivi du sous-directeur,
débouchait en coup de vent. Très haut, le cou dans les épaules, le
poil dru et blanc, il fonçait devant lui avec une force d'énergie
tenace, d'autorité bourrue. A la vue d'Hélène, il tourna la tête, car il
n'aimait pas la voir à l'usine. André s'élança pour le rejoindre.
Elle se sentit très seule, et tandis qu'elle regagnait sa barque,
traversait l'eau, le poids des misères coudoyées retomba sur elle en
tristesse que peu à peu dissipaient le recueillement du jardin,
l'aspect cordial de la vieille maison. Sa mère lui ouvrait les bras : —
« Chère grande fille! » M. Dugast la regardait plus tendrement que
de coutume ; jusqu'aux mains froides du grand-père Pierron qui
eurent un serrement affectueux. Une corbeille d'œillets magnifiques,
le cristal luisant des coupes à champagne donnaient un petit air de
fête à la salle à manger. La grand'mère Zoé, souffrant de sa
sciatique, gardait la chambre ; Hélène courut l'embrasser. André
avait prévenu qu'on ne l'attendît pas, il déjeunerait sans doute à la
Chesnaye.
A table, comme son père la taquinait amicalement, avec sa
philosophie souriante d'ancien diplomate qui avait séjourné
longuement dans des pays divers et vu de près, sous la différence
des mœurs, l'humanité toujours pareille, elle ne put taire davantage
sa révolte, l'injustice criante de la société. Sur trois de ses protégées,
l'une, épuisée de fatigue, avec son mari infirme, se trouvait sans
ressources, parce qu'elle devenait mère ; la seconde était livrée aux
rapines de son mari ; la dernière, veuve, s'exténuait pour faire vivre
son père impotent et ses petits. N'était-il pas honteux qu'aucune loi,
en France, ne secourût l'ouvrière qui enfante, la femme
abandonnée, l'invalide du travail?
La voix sèche de M. Pierron s'éleva avec un peu de cette gravité
solennelle qu'il mettait naguère, inflexible interprète du Code, à
requérir l'application des lois. Les lois! C'était son domaine, son bien,
sa vie. Nul ne connaissait comme lui l'inextricable dédale, les coins
obscurs pleins de traquenards et de précipices, le fourré, les sentiers
sinueux ou les chemins battus de cette forêt séculaire, immense. Le
hérissement des textes, les sables mouvants de la jurisprudence
n'avaient point de secret pour lui. Il s'y promenait à l'aise, avec une
joie de chasseur, un orgueil de propriétaire. Son père n'était-il pas ce
fameux Onésime Pierron, le farouche conventionnel mort dans l'habit
brodé d'un pair de Louis-Philippe, qui, avec Tronchet, Portalis, Bigot
de Préameneu, avait, sous le dur regard de Napoléon, contribué le
plus à défricher, à replanter l'antique forêt du droit?
— La loi, fit-il choqué de la liberté d'Hélène, ne peut pourtant pas
devenir sage-femme ou nourrice. Tu veux peut-être que les patrons
fassent des rentes à tous les enfants de leurs ouvriers? Leur fortune
n'y suffirait pas. Quand on n'est pas en situation, comme dit Émile
Augier, de se payer le luxe d'un garçon, c'est une imprévoyance
coupable, que dis-je, c'est un crime d'en avoir!
M. Dugast sourit, Pierron allait un peu loin. Hélène secouait la
tête sans répondre, un beau mépris sur son visage.
— Quant à ta femme abandonnée que le mari gruge, c'est
malheureux, mais c'est comme ça. Et depuis des siècles! C'est une
des conséquences du vieux texte : Feminis propter sexus
infirmitatem… D'ailleurs, ajouta-t-il dédaigneux, — il avait pour les
lois nouvelles une méfiance instinctive depuis qu'il n'était plus chargé
de les appliquer, — tranquillise-toi, il y a dans les cartons du Sénat
une proposition à l'étude, qui a pour but de garantir le salaire de
l'épouse, et l'autorise, en certains cas, à saisir-arrêter celui du mari.
— Je sais, répondit-elle, la proposition Jourdan-Goirand. Voilà
plus de huit ans que, grâce à l'initiative d'une vaillante, Mme
Schmahl…
— Mais, dit M. Dugast, la Chambre a émis un vote favorable.
— Reste le Sénat, fit Hélène. Et avec ironie :
— Depuis des mois et des mois, ces messieurs de la commission
y réfléchissent.
M. Pierron répliqua :
— Les lois ne se font pas comme ces crêpes, en un tour de main.
Il en roulait soigneusement une, dans son assiette, en la
saupoudrant de sucre. Il ajouta :
— Il y a temps pour tout.
— Et cependant, les malheureux souffrent!
M. Pierron, avec flegme, déclara entre deux bouchées :
— C'est leur lot, ma fille ; et tous les socialismes auront beau
faire, il y aura toujours des pauvres.
— Voyez-vous, dit malicieusement M. Dugast, cette petite qui
veut changer le train du monde!
Mme Dugast, qui ne se mêlait jamais aux discussions, approuva
d'un signe de tête. Qu'y faire? C'était ainsi. Le bruit discret du
champagne qu'on débouchait fit diversion ; on but aux vingt et un
ans d'Hélène.
IV
« Le Vert-Logis, 8 octobre.
« Ma chère tante,
« Hélène. »
VI