100% found this document useful (1 vote)
67 views76 pages

Programming in Scala Fifth Edition 5th Edition Martin Odersky Instant Download

The document discusses the fifth edition of 'Programming in Scala' by Martin Odersky, Lex Spoon, and Bill Venners, which is updated for Scala 3.0. It includes praise from various professionals highlighting the book's clarity, depth, and effectiveness as a tutorial for learning Scala. Additionally, it provides links to other Scala-related resources and books for further exploration.

Uploaded by

cxxkjhw3169
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
67 views76 pages

Programming in Scala Fifth Edition 5th Edition Martin Odersky Instant Download

The document discusses the fifth edition of 'Programming in Scala' by Martin Odersky, Lex Spoon, and Bill Venners, which is updated for Scala 3.0. It includes praise from various professionals highlighting the book's clarity, depth, and effectiveness as a tutorial for learning Scala. Additionally, it provides links to other Scala-related resources and books for further exploration.

Uploaded by

cxxkjhw3169
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Programming In Scala Fifth Edition 5th Edition

Martin Odersky download

https://ebookbell.com/product/programming-in-scala-fifth-
edition-5th-edition-martin-odersky-33360326

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Programming In Scala A Comprehensive Stepbystep Guide 2nd Edition 2nd


Edition Martin Odersky

https://ebookbell.com/product/programming-in-scala-a-comprehensive-
stepbystep-guide-2nd-edition-2nd-edition-martin-odersky-2544472

Programming In Scala A Comprehensive Stepbystep Guide Odersky M

https://ebookbell.com/product/programming-in-scala-a-comprehensive-
stepbystep-guide-odersky-m-2598228

Programming In Scala Updated For Scala 212 3rd Edition Martin Odersky

https://ebookbell.com/product/programming-in-scala-updated-for-
scala-212-3rd-edition-martin-odersky-5196380

Programming In Scala A Comprehensive Stepbystep Guide Third Edition


Martin Odersky

https://ebookbell.com/product/programming-in-scala-a-comprehensive-
stepbystep-guide-third-edition-martin-odersky-5903268
Functional Programming In Scala Second Edition Meap V08 2nd All
Chapters Available Michael Pilquist

https://ebookbell.com/product/functional-programming-in-scala-second-
edition-meap-v08-2nd-all-chapters-available-michael-pilquist-47503176

Functional Programming In Scala Meap V10 Paul Chiusano Runar Bjarnason

https://ebookbell.com/product/functional-programming-in-scala-
meap-v10-paul-chiusano-runar-bjarnason-36703538

Functional Programming In Scala Second Edition Michael Pilquistpaul


Chiusano Rnar Bjarnasson Paul Chiusano

https://ebookbell.com/product/functional-programming-in-scala-second-
edition-michael-pilquistpaul-chiusano-rnar-bjarnasson-paul-
chiusano-231980314

Learning Concurrent Programming In Scala Second Edition 2nd Edition


Aleksandar Prokopec

https://ebookbell.com/product/learning-concurrent-programming-in-
scala-second-edition-2nd-edition-aleksandar-prokopec-42970064

Learning Concurrent Programming In Scala 2nd Prokopec Aleksandar

https://ebookbell.com/product/learning-concurrent-programming-in-
scala-2nd-prokopec-aleksandar-6858126
A comprehensive step-by-step guide

Programming in

Scala Fifth Edition

Updated for Scala 3.0

Martin Odersky
Lex Spoon
artima Bill Venners
Frank Sommers
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


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 explana-
tions. 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 organi-
zation 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
Prepared for 138040

Scala language.
- Matthew Todd

Cover · Overview · Contents · 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 Plat-
form: 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 implement-
ing 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 im-
portantly, 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 program-


mers. 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 be-
tween giving too much or not enough information. I find Programming in
Prepared for 138040

Scala to achieve a perfect balance.


- Jeff Heon, Programmer Analyst

Cover · Overview · Contents · 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 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.
Prepared for 138040

- Igor Khlystov, Software Architect/Lead Programmer, Greystone Inc.

Cover · Overview · Contents · Suggest · Glossary · Index


v

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) at-
tempt 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
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Programming in Scala
Fifth Edition
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Programming in Scala
Fifth Edition
Martin Odersky, Lex Spoon, Bill Venners,
and Frank Sommers

artima
Prepared for 138040

A RTIMA P RESS
WALNUT C REEK , C ALIFORNIA

Cover · Overview · Contents · Suggest · Glossary · Index


viii

Programming in Scala
Fifth 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. Frank Sommers is
president of Autospaces, Inc.

Artima Press is an imprint of Artima, Inc.


2070 N Broadway Unit 305, Walnut Creek, California 94597

Copyright © 2007-2021 Martin Odersky, Lex Spoon, Bill Venners,


and Frank Sommers. All rights reserved.

First edition published as PrePrint™ eBook 2007


First edition published 2008
Second edition published 2010
Third edition published 2016
Fourth edition published 2019
Fifth edition published as PrePrint™ eBook 2021
Build date of this impression June 14, 2021
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.
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


to Nastaran - M.O.
to Fay - L.S.
to Siew - B.V.
to Jungwon - F.S.
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Overview
Contents xi
List of Figures xix
List of Tables xxi
List of Listings xxiii
Foreword xxix
Acknowledgments xxxiii
Introduction xxxvi
1. A Scalable Language 43
2. First Steps in Scala 61
3. Next Steps in Scala 74
4. Classes and Objects 95
5. Basic Types and Operations 108
6. Functional Objects 129
7. Built-in Control Structures 149
8. Functions and Closures 172
9. Control Abstraction 192
10. Composition and Inheritance 206
11. Traits 234
12. Packages, Imports, and Exports 251
13. Pattern Matching 270
14. Working with Lists 304
15. Working with Other Collections 335
16. Mutable Objects 355
17. Scala’s Hierarchy 378
18. Type Parameterization 394
19. Enums 416
20. Abstract Members 428
21. Givens 455
22. Extension Methods 477
23. Typeclasses 493
24. Collections in Depth 525
25. Assertions and Tests 589
Glossary 601
Bibliography 617
About the Authors 621
Index 622
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Contents

Contents xi

List of Figures xix

List of Tables xxi

List of Listings xxiii

Foreword xxix

Acknowledgments xxxiii

Introduction xxxvi

1 A Scalable Language 43
1.1 A language that grows on you . . . . . . . . . . . . . . 44
1.2 What makes Scala scalable? . . . . . . . . . . . . . . . 47
1.3 Why Scala? . . . . . . . . . . . . . . . . . . . . . . . . 51
1.4 Scala’s roots . . . . . . . . . . . . . . . . . . . . . . . 58
1.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 59

2 First Steps in Scala 61


Step 1. Learn to use the Scala REPL . . . . . . . . . . . . . . 61
Step 2. Define some variables . . . . . . . . . . . . . . . . . 63
Step 3. Define some functions . . . . . . . . . . . . . . . . . 65
Step 4. Write some Scala scripts . . . . . . . . . . . . . . . . 67
Prepared for 138040

Step 5. Loop with while; decide with if . . . . . . . . . . . 68


Step 6. Iterate with foreach and for-do . . . . . . . . . . . . 71
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xii

3 Next Steps in Scala 74


Step 7. Parameterize arrays with types . . . . . . . . . . . . 74
Step 8. Use lists . . . . . . . . . . . . . . . . . . . . . . . . 78
Step 9. Use tuples . . . . . . . . . . . . . . . . . . . . . . . 83
Step 10. Use sets and maps . . . . . . . . . . . . . . . . . . . 84
Step 11. Learn to recognize the functional style . . . . . . . . 88
Step 12. Transform with map and for-yield . . . . . . . . . . 91
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

4 Classes and Objects 95


4.1 Classes, fields, and methods . . . . . . . . . . . . . . . 95
4.2 Semicolon inference . . . . . . . . . . . . . . . . . . . 99
4.3 Singleton objects . . . . . . . . . . . . . . . . . . . . . 100
4.4 Case classes . . . . . . . . . . . . . . . . . . . . . . . 103
4.5 A Scala application . . . . . . . . . . . . . . . . . . . 105
4.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 107

5 Basic Types and Operations 108


5.1 Some basic types . . . . . . . . . . . . . . . . . . . . . 108
5.2 Literals . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.3 String interpolation . . . . . . . . . . . . . . . . . . . 114
5.4 Operators are methods . . . . . . . . . . . . . . . . . . 116
5.5 Arithmetic operations . . . . . . . . . . . . . . . . . . 119
5.6 Relational and logical operations . . . . . . . . . . . . 120
5.7 Bitwise operations . . . . . . . . . . . . . . . . . . . . 121
5.8 Object equality . . . . . . . . . . . . . . . . . . . . . . 122
5.9 Operator precedence and associativity . . . . . . . . . . 124
5.10 Rich operations . . . . . . . . . . . . . . . . . . . . . 127
5.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 127

6 Functional Objects 129


6.1 A specification for class Rational . . . . . . . . . . . 129
6.2 Constructing a Rational . . . . . . . . . . . . . . . . 130
6.3 Reimplementing the toString method . . . . . . . . . 132
6.4 Checking preconditions . . . . . . . . . . . . . . . . . 133
Prepared for 138040

6.5 Adding fields . . . . . . . . . . . . . . . . . . . . . . . 134


6.6 Self references . . . . . . . . . . . . . . . . . . . . . . 136
6.7 Auxiliary constructors . . . . . . . . . . . . . . . . . . 136

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xiii

6.8 Private fields and methods . . . . . . . . . . . . . . . . 138


6.9 Defining operators . . . . . . . . . . . . . . . . . . . . 139
6.10 Identifiers in Scala . . . . . . . . . . . . . . . . . . . . 141
6.11 Method overloading . . . . . . . . . . . . . . . . . . . 144
6.12 Extension methods . . . . . . . . . . . . . . . . . . . . 146
6.13 A word of caution . . . . . . . . . . . . . . . . . . . . 147
6.14 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 147

7 Built-in Control Structures 149


7.1 If expressions . . . . . . . . . . . . . . . . . . . . . . 150
7.2 While loops . . . . . . . . . . . . . . . . . . . . . . . 151
7.3 For expressions . . . . . . . . . . . . . . . . . . . . . . 154
7.4 Exception handling with try expressions . . . . . . . . 159
7.5 Match expressions . . . . . . . . . . . . . . . . . . . . 163
7.6 Living without break and continue . . . . . . . . . . 164
7.7 Variable scope . . . . . . . . . . . . . . . . . . . . . . 166
7.8 Refactoring imperative-style code . . . . . . . . . . . . 169
7.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 171

8 Functions and Closures 172


8.1 Methods . . . . . . . . . . . . . . . . . . . . . . . . . 172
8.2 Local functions . . . . . . . . . . . . . . . . . . . . . . 173
8.3 First-class functions . . . . . . . . . . . . . . . . . . . 175
8.4 Short forms of function literals . . . . . . . . . . . . . 176
8.5 Placeholder syntax . . . . . . . . . . . . . . . . . . . . 177
8.6 Partially applied functions . . . . . . . . . . . . . . . . 178
8.7 Closures . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.8 Special function call forms . . . . . . . . . . . . . . . 183
8.9 “SAM” types . . . . . . . . . . . . . . . . . . . . . . . 186
8.10 Tail recursion . . . . . . . . . . . . . . . . . . . . . . . 188
8.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 191

9 Control Abstraction 192


9.1 Reducing code duplication . . . . . . . . . . . . . . . . 192
9.2 Simplifying client code . . . . . . . . . . . . . . . . . 196
Prepared for 138040

9.3 Currying . . . . . . . . . . . . . . . . . . . . . . . . . 198


9.4 Writing new control structures . . . . . . . . . . . . . . 199
9.5 By-name parameters . . . . . . . . . . . . . . . . . . . 202

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xiv

9.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 204

10 Composition and Inheritance 206


10.1 A two-dimensional layout library . . . . . . . . . . . . 206
10.2 Abstract classes . . . . . . . . . . . . . . . . . . . . . 207
10.3 Defining parameterless methods . . . . . . . . . . . . . 208
10.4 Extending classes . . . . . . . . . . . . . . . . . . . . 211
10.5 Overriding methods and fields . . . . . . . . . . . . . . 213
10.6 Defining parametric fields . . . . . . . . . . . . . . . . 214
10.7 Invoking superclass constructors . . . . . . . . . . . . . 216
10.8 Using override modifiers . . . . . . . . . . . . . . . . 217
10.9 Polymorphism and dynamic binding . . . . . . . . . . 219
10.10 Declaring final members . . . . . . . . . . . . . . . . . 221
10.11 Using composition and inheritance . . . . . . . . . . . 222
10.12 Implementing above, beside, and toString . . . . . . 224
10.13 Defining a factory object . . . . . . . . . . . . . . . . . 226
10.14 Heighten and widen . . . . . . . . . . . . . . . . . . . 228
10.15 Putting it all together . . . . . . . . . . . . . . . . . . . 230
10.16 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 233

11 Traits 234
11.1 How traits work . . . . . . . . . . . . . . . . . . . . . 234
11.2 Thin versus rich interfaces . . . . . . . . . . . . . . . . 237
11.3 Traits as stackable modifications . . . . . . . . . . . . . 239
11.4 Why not multiple inheritance? . . . . . . . . . . . . . . 243
11.5 Trait parameters . . . . . . . . . . . . . . . . . . . . . 248
11.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 250

12 Packages, Imports, and Exports 251


12.1 Putting code in packages . . . . . . . . . . . . . . . . . 251
12.2 Concise access to related code . . . . . . . . . . . . . . 252
12.3 Imports . . . . . . . . . . . . . . . . . . . . . . . . . . 256
12.4 Implicit imports . . . . . . . . . . . . . . . . . . . . . 259
12.5 Access modifiers . . . . . . . . . . . . . . . . . . . . . 260
12.6 Top-level definitions . . . . . . . . . . . . . . . . . . . 265
Prepared for 138040

12.7 Exports . . . . . . . . . . . . . . . . . . . . . . . . . . 266


12.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 269

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xv

13 Pattern Matching 270


13.1 A simple example . . . . . . . . . . . . . . . . . . . . 270
13.2 Kinds of patterns . . . . . . . . . . . . . . . . . . . . . 274
13.3 Pattern guards . . . . . . . . . . . . . . . . . . . . . . 284
13.4 Pattern overlaps . . . . . . . . . . . . . . . . . . . . . 285
13.5 Sealed classes . . . . . . . . . . . . . . . . . . . . . . 287
13.6 Pattern matching Options . . . . . . . . . . . . . . . . 289
13.7 Patterns everywhere . . . . . . . . . . . . . . . . . . . 291
13.8 A larger example . . . . . . . . . . . . . . . . . . . . . 295
13.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 303

14 Working with Lists 304


14.1 List literals . . . . . . . . . . . . . . . . . . . . . . . . 304
14.2 The List type . . . . . . . . . . . . . . . . . . . . . . 305
14.3 Constructing lists . . . . . . . . . . . . . . . . . . . . . 305
14.4 Basic operations on lists . . . . . . . . . . . . . . . . . 306
14.5 List patterns . . . . . . . . . . . . . . . . . . . . . . . 307
14.6 First-order methods on class List . . . . . . . . . . . . 309
14.7 Higher-order methods on class List . . . . . . . . . . 320
14.8 Methods of the List object . . . . . . . . . . . . . . . 327
14.9 Processing multiple lists together . . . . . . . . . . . . 329
14.10 Understanding Scala’s type inference algorithm . . . . 331
14.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 334

15 Working with Other Collections 335


15.1 Sequences . . . . . . . . . . . . . . . . . . . . . . . . 335
15.2 Sets and maps . . . . . . . . . . . . . . . . . . . . . . 339
15.3 Selecting mutable versus immutable collections . . . . 346
15.4 Initializing collections . . . . . . . . . . . . . . . . . . 348
15.5 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . 351
15.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 353

16 Mutable Objects 355


16.1 What makes an object mutable? . . . . . . . . . . . . . 355
16.2 Reassignable variables and properties . . . . . . . . . . 357
Prepared for 138040

16.3 Case study: Discrete event simulation . . . . . . . . . . 361


16.4 A language for digital circuits . . . . . . . . . . . . . . 362
16.5 The Simulation API . . . . . . . . . . . . . . . . . . 365

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xvi

16.6 Circuit Simulation . . . . . . . . . . . . . . . . . . . . 369


16.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 376

17 Scala’s Hierarchy 378


17.1 Scala’s class hierarchy . . . . . . . . . . . . . . . . . . 378
17.2 How primitives are implemented . . . . . . . . . . . . 382
17.3 Bottom types . . . . . . . . . . . . . . . . . . . . . . . 384
17.4 Defining your own value classes . . . . . . . . . . . . . 385
17.5 Intersection types . . . . . . . . . . . . . . . . . . . . 388
17.6 Union types . . . . . . . . . . . . . . . . . . . . . . . 389
17.7 Transparent traits . . . . . . . . . . . . . . . . . . . . . 392
17.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 393

18 Type Parameterization 394


18.1 Functional queues . . . . . . . . . . . . . . . . . . . . 394
18.2 Information hiding . . . . . . . . . . . . . . . . . . . . 397
18.3 Variance annotations . . . . . . . . . . . . . . . . . . . 400
18.4 Checking variance annotations . . . . . . . . . . . . . 405
18.5 Lower bounds . . . . . . . . . . . . . . . . . . . . . . 408
18.6 Contravariance . . . . . . . . . . . . . . . . . . . . . . 409
18.7 Upper bounds . . . . . . . . . . . . . . . . . . . . . . 413
18.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 415

19 Enums 416
19.1 Enumerated data types . . . . . . . . . . . . . . . . . . 416
19.2 Algebraic data types . . . . . . . . . . . . . . . . . . . 420
19.3 Generalized ADTs . . . . . . . . . . . . . . . . . . . . 422
19.4 What makes ADTs algebraic . . . . . . . . . . . . . . 423
19.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 427

20 Abstract Members 428


20.1 A quick tour of abstract members . . . . . . . . . . . . 428
20.2 Type members . . . . . . . . . . . . . . . . . . . . . . 429
20.3 Abstract vals . . . . . . . . . . . . . . . . . . . . . . 430
20.4 Abstract vars . . . . . . . . . . . . . . . . . . . . . . 430
20.5 Initializing abstract vals . . . . . . . . . . . . . . . . . 432
Prepared for 138040

20.6 Abstract types . . . . . . . . . . . . . . . . . . . . . . 439


20.7 Path-dependent types . . . . . . . . . . . . . . . . . . 441

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xvii

20.8 Refinement types . . . . . . . . . . . . . . . . . . . . . 444


20.9 Case study: Currencies . . . . . . . . . . . . . . . . . . 445
20.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 453

21 Givens 455
21.1 How it works . . . . . . . . . . . . . . . . . . . . . . . 455
21.2 Parameterized given types . . . . . . . . . . . . . . . . 459
21.3 Anonymous givens . . . . . . . . . . . . . . . . . . . . 464
21.4 Parameterized givens as typeclasses . . . . . . . . . . . 465
21.5 Given imports . . . . . . . . . . . . . . . . . . . . . . 468
21.6 Rules for context parameters . . . . . . . . . . . . . . . 469
21.7 When multiple givens apply . . . . . . . . . . . . . . . 472
21.8 Debugging givens . . . . . . . . . . . . . . . . . . . . 474
21.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 476

22 Extension Methods 477


22.1 The basics . . . . . . . . . . . . . . . . . . . . . . . . 477
22.2 Generic extensions . . . . . . . . . . . . . . . . . . . . 480
22.3 Collective extensions . . . . . . . . . . . . . . . . . . . 481
22.4 Using a typeclass . . . . . . . . . . . . . . . . . . . . . 484
22.5 Extension methods for givens . . . . . . . . . . . . . . 486
22.6 Where Scala looks for extension methods . . . . . . . . 490
22.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 491

23 Typeclasses 493
23.1 Why typeclasses? . . . . . . . . . . . . . . . . . . . . 493
23.2 Context bounds . . . . . . . . . . . . . . . . . . . . . . 498
23.3 Main methods . . . . . . . . . . . . . . . . . . . . . . 501
23.4 Multiversal equality . . . . . . . . . . . . . . . . . . . 505
23.5 Implicit conversions . . . . . . . . . . . . . . . . . . . 511
23.6 Typeclass case study: JSON serialization . . . . . . . . 514
23.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 523

24 Collections in Depth 525


24.1 Mutable and immutable collections . . . . . . . . . . . 526
24.2 Collections consistency . . . . . . . . . . . . . . . . . 528
Prepared for 138040

24.3 Trait Iterable . . . . . . . . . . . . . . . . . . . . . . 530


24.4 The sequence traits Seq, IndexedSeq, and LinearSeq . 537

Cover · Overview · Contents · Suggest · Glossary · Index


Contents xviii

24.5 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544


24.6 Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
24.7 Concrete immutable collection classes . . . . . . . . . 552
24.8 Concrete mutable collection classes . . . . . . . . . . . 559
24.9 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 564
24.10 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 568
24.11 Performance characteristics . . . . . . . . . . . . . . . 569
24.12 Equality . . . . . . . . . . . . . . . . . . . . . . . . . 571
24.13 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
24.14 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . 576
24.15 Creating collections from scratch . . . . . . . . . . . . 584
24.16 Conversions between Java and Scala collections . . . . 586
24.17 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 588

25 Assertions and Tests 589


25.1 Assertions . . . . . . . . . . . . . . . . . . . . . . . . 589
25.2 Testing in Scala . . . . . . . . . . . . . . . . . . . . . 591
25.3 Informative failure reports . . . . . . . . . . . . . . . . 592
25.4 Tests as specifications . . . . . . . . . . . . . . . . . . 594
25.5 Property-based testing . . . . . . . . . . . . . . . . . . 597
25.6 Organizing and running tests . . . . . . . . . . . . . . 599
25.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 600

Glossary 601

Bibliography 617

About the Authors 621

Index 622
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


List of Figures

1 What was intended. . . . . . . . . . . . . . . . . . . . . . . xxxi


2 What we got. . . . . . . . . . . . . . . . . . . . . . . . . . xxxi

2.1 The basic form of a function definition in Scala. . . . . . . . 66


2.2 The syntax of a function literal in Scala. . . . . . . . . . . . 72

3.1 All operations are method calls in Scala. . . . . . . . . . . . 77


3.2 Class hierarchy for Scala sets. . . . . . . . . . . . . . . . . 85
3.3 Class hierarchy for Scala maps. . . . . . . . . . . . . . . . . 87

10.1 Class diagram for VectorElement. . . . . . . . . . . . . . 212


10.2 Class diagram for LineElement. . . . . . . . . . . . . . . . 217
10.3 Class hierarchy of layout elements. . . . . . . . . . . . . . . 220
10.4 Class hierarchy with revised LineElement. . . . . . . . . . 223

11.1 Inheritance hierarchy and linearization of class Cat. . . . . . 246

16.1 Basic gates. . . . . . . . . . . . . . . . . . . . . . . . . . . 362


16.2 A half-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 363
16.3 A full-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 364

17.1 Class hierarchy of Scala. . . . . . . . . . . . . . . . . . . . 380


17.2 Least upper and greatest lower bounds. . . . . . . . . . . . . 390

18.1 Covariance and contravariance in function type parameters. . 412

23.1 Set of types accepted by Int’s minus (-) methods. . . . . . . 494


Prepared for 138040

23.2 Set of types accepted by the paint method. . . . . . . . . . 495


23.3 Set of types T with given instances of Ordering[T]. . . . . 498
23.4 Set of types T with given instances of FromString[T]. . . . 505

xix
Contents xx

24.1 Collection hierarchy. . . . . . . . . . . . . . . . . . . . . . 529

25.1 The output of org.scalatest.run. . . . . . . . . . . . . . 600


Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


List of Tables

3.1 Some List methods and usages . . . . . . . . . . . . . . . 81

5.1 Some basic types . . . . . . . . . . . . . . . . . . . . . . . 109


5.2 Special character literal escape sequences . . . . . . . . . . 113
5.3 Operator precedence . . . . . . . . . . . . . . . . . . . . . 125
5.4 Some rich operations . . . . . . . . . . . . . . . . . . . . 127
5.5 Rich wrapper classes . . . . . . . . . . . . . . . . . . . . . 128

11.1 Linearization of types in Cat’s hierarchy . . . . . . . . . . 247

12.1 Effects of private qualifiers on LegOfJourney.distance . 263

14.1 Basic list operations . . . . . . . . . . . . . . . . . . . . . 307

15.1 Common operations for sets . . . . . . . . . . . . . . . . . 341


15.2 Common operations for maps . . . . . . . . . . . . . . . . 343
15.3 Default immutable set implementations . . . . . . . . . . . 345
15.4 Default immutable map implementations . . . . . . . . . . 345

19.1 The cardinality of Hope . . . . . . . . . . . . . . . . . . . 425


19.2 The cardinality of Both . . . . . . . . . . . . . . . . . . . 426

24.1 Operations in trait Iterable . . . . . . . . . . . . . . . . 532


24.2 Operations in trait Seq . . . . . . . . . . . . . . . . . . . 539
24.3 Operations in trait mutable.IndexedSeq . . . . . . . . . 542
24.4 Operations in trait Buffer . . . . . . . . . . . . . . . . . 543
24.5 Operations in trait Set . . . . . . . . . . . . . . . . . . . 544
Prepared for 138040

24.6 Operations in trait immutable.Set . . . . . . . . . . . . . 545


24.7 Operations in trait mutable.Set . . . . . . . . . . . . . . 545
24.8 Operations in trait Map . . . . . . . . . . . . . . . . . . . 549

xxi
Contents xxii

24.9 Operations in trait immutable.Map . . . . . . . . . . . . . 549


24.10 Operations in trait mutable.Map . . . . . . . . . . . . . . 550
24.11 Operations in trait concurrent.Map . . . . . . . . . . . . 563
24.12 Performance characteristics of sequence types . . . . . . . 569
24.13 Performance characteristics of set and map types . . . . . . 570
24.14 Operations in trait Iterator . . . . . . . . . . . . . . . . 579
24.15 Factory methods for Seqs and Sets . . . . . . . . . . . . . 585
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


List of Listings

3.1 Parameterizing an array with a type. . . . . . . . . . . . . 75


3.2 Creating and initializing an array. . . . . . . . . . . . . . . 78
3.3 Creating and initializing a list. . . . . . . . . . . . . . . . . 79
3.4 Creating and using a tuple. . . . . . . . . . . . . . . . . . 83
3.5 Creating, initializing, and using an immutable set. . . . . . 84
3.6 Creating, initializing, and using a mutable set. . . . . . . . 85
3.7 Creating, initializing, and using a mutable map. . . . . . . 87
3.8 Creating, initializing, and using an immutable map. . . . . 88
3.9 A function without side effects or vars. . . . . . . . . . . . 90

4.1 Final version of class ChecksumAccumulator. . . . . . . . 99


4.2 Companion object for class ChecksumAccumulator. . . . . 101
4.3 The Summer application. . . . . . . . . . . . . . . . . . . . 105

6.1 Rational with fields. . . . . . . . . . . . . . . . . . . . . 135


6.2 Rational with an auxiliary constructor. . . . . . . . . . . 137
6.3 Rational with a private field and method. . . . . . . . . . 139
6.4 Rational with operator methods. . . . . . . . . . . . . . . 140
6.5 Rational with overloaded methods. . . . . . . . . . . . . 145

7.1 Scala’s idiom for conditional initialization. . . . . . . . . . 150


7.2 Calculating greatest common divisor with a while loop. . . 151
7.3 Executing a loop body at least once without do-while. . . 152
7.4 Calculating greatest common divisor with recursion. . . . . 153
7.5 Listing files in a directory with a for expression. . . . . . . 154
7.6 Finding .scala files using a for with a filter. . . . . . . . 156
Prepared for 138040

7.7 Using multiple filters in a for expression. . . . . . . . . . 156


7.8 Using multiple generators in a for expression. . . . . . . . 157
7.9 Mid-stream assignment in a for expression. . . . . . . . . 158

xxiii
List of Listings xxiv

7.10 Transforming an Array[File] to Array[Int] with a for. 159


7.11 A try-catch clause in Scala. . . . . . . . . . . . . . . . . 160
7.12 A try-finally clause in Scala. . . . . . . . . . . . . . . 161
7.13 A catch clause that yields a value. . . . . . . . . . . . . . 162
7.14 A match expression with side effects. . . . . . . . . . . . . 163
7.15 A match expression that yields a value. . . . . . . . . . . . 164
7.16 Looping without break or continue. . . . . . . . . . . . . 165
7.17 A recursive alternative to looping with vars. . . . . . . . . 166
7.18 Variable scoping when printing a multiplication table. . . . 167
7.19 A functional way to create a multiplication table. . . . . . . 170

8.1 Padding with a private padLine method. . . . . . . . . . . 173


8.2 LongLines with a local processLine function. . . . . . . 174
8.3 A parameter with a default value. . . . . . . . . . . . . . . 186
8.4 A function with two parameters that have defaults. . . . . . 186

9.1 Using closures to reduce code duplication. . . . . . . . . . 195


9.2 Defining and invoking a “plain old” function. . . . . . . . . 198
9.3 Defining and invoking a curried function. . . . . . . . . . . 198
9.4 Using the loan pattern to write to a file. . . . . . . . . . . . 202
9.5 Using a by-name parameter. . . . . . . . . . . . . . . . . . 203

10.1 Defining an abstract method and class. . . . . . . . . . . . 208


10.2 Defining parameterless methods width and height. . . . . 209
10.3 Defining VectorElement as a subclass of Element. . . . . 211
10.4 Overriding a parameterless method with a field. . . . . . . 213
10.5 Defining contents as a parametric field. . . . . . . . . . . 215
10.6 Invoking a superclass constructor. . . . . . . . . . . . . . . 216
10.7 Declaring a final method. . . . . . . . . . . . . . . . . . . 221
10.8 Declaring a final class. . . . . . . . . . . . . . . . . . . . . 222
10.9 Class Element with above, beside, and toString. . . . . 226
10.10 A factory object with factory methods. . . . . . . . . . . . 227
10.11 Class Element refactored to use factory methods. . . . . . 228
10.12 Hiding implementation with private classes. . . . . . . . . 229
10.13 Element with widen and heighten methods. . . . . . . . 231
10.14 The Spiral application. . . . . . . . . . . . . . . . . . . . 232
Prepared for 138040

11.1 The definition of trait Philosophical. . . . . . . . . . . . 234


11.2 Mixing in a trait using extends. . . . . . . . . . . . . . . 235

Cover · Overview · Contents · Suggest · Glossary · Index


List of Listings xxv

11.3 Mixing in a trait using a comma. . . . . . . . . . . . . . . 235


11.4 Mixing in multiple traits. . . . . . . . . . . . . . . . . . . 236
11.5 Abstract class IntQueue. . . . . . . . . . . . . . . . . . . 240
11.6 A BasicIntQueue implemented with an ArrayBuffer. . . 240
11.7 The Doubling stackable modification trait. . . . . . . . . . 241
11.8 Mixing in a trait when instantiating with new. . . . . . . . . 242
11.9 Stackable modification traits Incrementing and Filtering. 242
11.10 Defining a trait parameter. . . . . . . . . . . . . . . . . . . 248
11.11 Supplying a trait parameter. . . . . . . . . . . . . . . . . . 249
11.12 Not supplying a trait parameter. . . . . . . . . . . . . . . . 249

12.1 Placing the contents of an entire file into a package. . . . . 252


12.2 Long form of a simple package declaration. . . . . . . . . 252
12.3 Multiple packages in the same file. . . . . . . . . . . . . . 253
12.4 Concise access to classes and packages. . . . . . . . . . . . 253
12.5 Symbols in enclosing packages not automatically available. 253
12.6 Accessing hidden package names. . . . . . . . . . . . . . . 254
12.7 Bob’s delightful fruits, ready for import. . . . . . . . . . . 256
12.8 Importing the members of a regular (not singleton) object. . 257
12.9 Importing a package name. . . . . . . . . . . . . . . . . . 258
12.10 How private access differs in Scala and Java. . . . . . . . . 261
12.11 How protected access differs in Scala and Java. . . . . . . . 261
12.12 Flexible scope of protection with access qualifiers. . . . . . 262
12.13 Accessing private members of companion classes and objects. 264
12.14 A package object. . . . . . . . . . . . . . . . . . . . . . . 265

13.1 Defining case classes. . . . . . . . . . . . . . . . . . . . . 271


13.2 The simplifyTop function, which does a pattern match. . . 273
13.3 A pattern match with an empty “default” case. . . . . . . . 274
13.4 A pattern match with wildcard patterns. . . . . . . . . . . . 275
13.5 A pattern match with constant patterns. . . . . . . . . . . . 276
13.6 A pattern match with a variable pattern. . . . . . . . . . . . 276
13.7 A pattern match with a constructor pattern. . . . . . . . . . 279
13.8 A sequence pattern with a fixed length. . . . . . . . . . . . 279
13.9 A sequence pattern with an arbitrary length. . . . . . . . . 279
Prepared for 138040

13.10 A pattern match with a tuple pattern. . . . . . . . . . . . . 280


13.11 A pattern match with typed patterns. . . . . . . . . . . . . 280
13.12 Using isInstanceOf and asInstanceOf (poor style). . . . 281

Cover · Overview · Contents · Suggest · Glossary · Index


List of Listings xxvi

13.13 A pattern with a variable binding (via the @ sign). . . . . . 284


13.14 A match expression with a pattern guard. . . . . . . . . . . 285
13.15 Match expression in which case order matters. . . . . . . . 286
13.16 A sealed hierarchy of case classes. . . . . . . . . . . . . . 288
13.17 Defining multiple variables with one assignment. . . . . . . 291
13.18 A for expression with a tuple pattern. . . . . . . . . . . . 294
13.19 Picking elements of a list that match a pattern. . . . . . . . 295
13.20 The top half of the expression formatter. . . . . . . . . . . 297
13.21 The bottom half of the expression formatter. . . . . . . . . 298
13.22 An application that prints formatted expressions. . . . . . . 302

14.1 Sorting a List[Int] via the insertion sort algorithm. . . . 307


14.2 A merge sort function for Lists. . . . . . . . . . . . . . . 319

15.1 Default map and set definitions in Predef. . . . . . . . . . 339

16.1 A mutable bank account class. . . . . . . . . . . . . . . . . 356


16.2 A class with public vars. . . . . . . . . . . . . . . . . . . 358
16.3 How public vars are expanded into getter and setter methods. 358
16.4 Defining getter and setter methods directly. . . . . . . . . . 359
16.5 Defining a getter and setter without an associated field. . . 360
16.6 The halfAdder method. . . . . . . . . . . . . . . . . . . . 363
16.7 The fullAdder method. . . . . . . . . . . . . . . . . . . . 364
16.8 The Simulation class. . . . . . . . . . . . . . . . . . . . 365
16.9 The first half of the BasicCircuitSimulation class. . . . 370
16.10 The second half of the BasicCircuitSimulation class. . 371
16.11 The CircuitSimulation class. . . . . . . . . . . . . . . . 375

18.1 A basic functional queue. . . . . . . . . . . . . . . . . . . 397


18.2 Hiding a primary constructor by making it private. . . . . . 398
18.3 An apply factory method in a companion object. . . . . . 399
18.4 Type abstraction for functional queues. . . . . . . . . . . . 400
18.5 A nonvariant (rigid) Cell class. . . . . . . . . . . . . . . . 402
18.6 A type parameter with a lower bound. . . . . . . . . . . . . 408
18.7 A contravariant output channel. . . . . . . . . . . . . . . . 410
18.8 Covariance and contravariance of Function1s. . . . . . . . 410
Prepared for 138040

18.9 Demonstration of function type parameter variance. . . . . 411


18.10 A Person class that mixes in the Ordered trait. . . . . . . 413
18.11 A merge sort function with an upper bound. . . . . . . . . 414

Cover · Overview · Contents · Suggest · Glossary · Index


List of Listings xxvii

20.1 Overriding abstract vals and parameterless methods. . . . 431


20.2 Declaring abstract vars. . . . . . . . . . . . . . . . . . . . 431
20.3 How abstract vars are expanded into getters and setters. . . 431
20.4 A trait that uses its abstract vals. . . . . . . . . . . . . . . 433
20.5 A trait that takes parametric fields. . . . . . . . . . . . . . 434
20.6 Trait parametric fields in an anonymous class expression. . 434
20.7 Trait parametric fields in an object definition. . . . . . . . . 435
20.8 Trait parametric fields in a class definition. . . . . . . . . . 435
20.9 Initializing a trait with lazy vals. . . . . . . . . . . . . . . 437
20.10 Modeling suitable food with an abstract type. . . . . . . . . 440
20.11 Implementing an abstract type in a subclass. . . . . . . . . 441
20.12 The US currency zone. . . . . . . . . . . . . . . . . . . . 450
20.13 Currency zones for Europe and Japan. . . . . . . . . . . . 452
20.14 A converter object with an exchange rates map. . . . . . . 453
20.15 The full code of class CurrencyZone. . . . . . . . . . . . 454

21.1 An implicit parameter list with multiple parameters. . . . . 458


21.2 Context parameters passed with using. . . . . . . . . . . . 462
21.3 Declaring a natural given in a companion. . . . . . . . . . 463
21.4 An insertion sort function that uses Ordering. . . . . . . . 467
21.5 A merge sort function that uses Ordering. . . . . . . . . . 467
21.6 A preferences object. . . . . . . . . . . . . . . . . . . . . 468
21.7 Multiple givens. . . . . . . . . . . . . . . . . . . . . . . . 472
21.8 Sample code that uses a context parameter. . . . . . . . . . 475
21.9 Sample code after type checking and insertion of givens. . . 475

22.1 An extension method for Strings. . . . . . . . . . . . . . 478


22.2 An extension method as rewritten by the compiler. . . . . . 479
22.3 A generic extension method. . . . . . . . . . . . . . . . . 481
22.4 A collective extension. . . . . . . . . . . . . . . . . . . . . 483
22.5 Invoking a sibling extension method. . . . . . . . . . . . . 483
22.6 A collective extension as rewritten by the compiler. . . . . 484
22.7 A typeclass for twos-complement numbers. . . . . . . . . . 485
22.8 Using a typeclass in an extension. . . . . . . . . . . . . . . 486
22.9 Placing extension methods in a singleton. . . . . . . . . . . 487
Prepared for 138040

22.10 Placing extensions for Ord in a singleton. . . . . . . . . . . 488


22.11 Placing an extension in a typeclass trait. . . . . . . . . . . 489
22.12 Using an extension defined in a typeclass trait. . . . . . . . 489

Cover · Overview · Contents · Suggest · Glossary · Index


List of Listings xxviii

22.13 Typeclass extensions as rewritten by the compiler. . . . . . 490

23.1 A given Ordering instance for Hope[T]. . . . . . . . . . . 497


23.2 A function with a using parameter. . . . . . . . . . . . . . 499
23.3 A function that uses a using parameter internally. . . . . . 500
23.4 A function that uses summon. . . . . . . . . . . . . . . . . 501
23.5 A function with a context bound. . . . . . . . . . . . . . . 502
23.6 The FromString typeclass trait. . . . . . . . . . . . . . . . 503
23.7 A Mood enum. . . . . . . . . . . . . . . . . . . . . . . . . 503
23.8 A main method that takes a custom type. . . . . . . . . . . 504
23.9 A given FromString instance for Mood. . . . . . . . . . . 504
23.10 The == and != methods in both Scala 2 and 3. . . . . . . . 507
23.11 An explicit CanEqual provider (not idiomatic). . . . . . . . 510
23.12 Offering CanEqual through a derives clause. . . . . . . . 510
23.13 A JSON serializer typeclass. . . . . . . . . . . . . . . . . . 515
23.14 A JSON serializer typeclass with an extension method. . . 515
23.15 JSON serializer companion object with givens. . . . . . . . 516
23.16 An extension method for convenient importing. . . . . . . 516
23.17 Case classes for an address book. . . . . . . . . . . . . . . 517
23.18 JSON serializers for Address and Phone. . . . . . . . . . . 518
23.19 Given JSON serializer for lists. . . . . . . . . . . . . . . . 519
23.20 Given JSON serializers for Contact and AddressBook. . . 521
23.21 An AddressBook. . . . . . . . . . . . . . . . . . . . . . . 522
23.22 JSON representation of an address book . . . . . . . . . . 523

25.1 Using an assertion. . . . . . . . . . . . . . . . . . . . . . . 590


25.2 Using ensuring to assert a function’s result. . . . . . . . . 590
25.3 Writing tests with AnyFunSuite. . . . . . . . . . . . . . . 591
25.4 Specifying and testing behavior with an AnyFlatSpec. . . 595
25.5 Specifying and testing behavior with the specs2 framework. 596
25.6 Using tests to facilitate communication among stakeholders. 597
25.7 Writing property-based tests with ScalaCheck. . . . . . . . 598
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Foreword

Watching the birth of a new programming language is a funny thing. To


anyone who uses a programming language—whether you are dabbling with
programming for the first time or are a grizzled career software engineer—
programming languages just seem to exist. Like a hammer or axe, a pro-
gramming language is a tool, already there, that enables us to perform our
trade. We seldom think of how that tool came to be, what the process was
to design it. We might have opinions about its design, but beyond that, we
usually just put up with it and push forward.
Being there as a programming language is created, however, brings a to-
tally different perspective. The possibilities for what could be seem endless.
Yet at the same time, the programming language must satisfy what seems
like an infinite list of constraints. It’s an odd tension.
New programming languages are created for many reasons: a personal
desire to scratch a niggling itch, a profound academic insight, technical debt,
or the benefit of hindsight of other compiler architectures—even politics.
Scala 3 is a combination of some of these.
Whatever combination it may be, it all started when Martin Odersky dis-
appeared one day, emerging a few days later to announce in a research group
meeting that he had begun experimenting with bringing the DOT calculus to
life by writing a new compiler from scratch.1 Here we were, a group of PhD
students and postdocs who had until recently been a big part of the devel-
opment and maintenance of Scala 2. At the time, Scala was reaching what
felt like unfathomable heights of success, especially for an esoteric and aca-
demic programming language from a school with a funny-sounding name in
Switzerland. Scala had recently taken off among startups in the Bay Area,
Prepared for 138040

and Typesafe, later named Lightbend, had recently been formed to support,
1 DOT, or dependent object types, calculus is a series of formalizations attempting to
characterize the essence of Scala’s type system.

Cover · Overview · Contents · Suggest · Glossary · Index


Foreword xxx

maintain, and manage releases of Scala 2. So why all of a sudden a new


compiler and possibly a new and different programming language? Most
were skeptical. Martin was undeterred.
Months passed. Like clockwork, at twelve noon every day, the entire
lab would gather in the hallway connecting all of our offices. After a fair
number of us and Martin had assembled, we’d venture together to one of
EPFL’s many cafeterias, grab lunch, and later, an after-lunch coffee. Each
day during this ritual, ideas for this new compiler were a recurrent theme.
Discussions would ping pong about, anywhere from focusing on something
“150%” compatible with Scala 2 (to avoid a Python 2 versus Python 3 deba-
cle), to creating new language with full-spectrum dependent types.
One by one, the skeptics in the research group seemed to become sold
by some appealing aspect of Scala 3, be it streamlining the implementation
of the typechecker, the brand new compiler architecture, or the powerful ad-
ditions to the type system. Over time, much of the community also came
around to the idea of Scala 3 being a marked improvement over Scala 2.
Different people had different reasons for this. For some, it was the im-
provements in readability via the decision to make braces and parentheses
around conditions in conditionals optional. For others, it was improvements
to the type system; for example, match types for improved type-level pro-
gramming. The list went on.
Rather than blindly steaming ahead on the design of Scala 3 based on
hunch alone, I can confidently assert that Scala 3 is the result of much learn-
ing from design decisions of the past, and years of conversation with the
EPFL research group and the Scala community. And there was no way but
to start from a clean slate, and build on clean foundations. With this from-
scratch approach, what emerged is, at its core, a new programming language.
Scala 3 is a new programming language. Sure, it might be compatible
with Scala 2, and it might sound like the third major release of an already-
existing programming language. But don’t let that fool you. Scala 3 repre-
sents a substantial streamlining of many of the experimental ideas pioneered
in Scala 2.
Perhaps what is most uniquely “Scala” about Scala 3 is what happened to
implicits. Scala, since its inception, has been used by clever programmers to
achieve functionality that few thought was even possible given Scala’s fea-
Prepared for 138040

ture set, let alone something Scala was designed for. The feature previously-
known as implicits is perhaps the most well-known feature of Scala that has
been exploited to bend Scala 2 in unexpected ways. Example use cases of
Cover · Overview · Contents · Suggest · Glossary · Index
Foreword xxxi

Figure 1 · What was intended. Figure 2 · What we got.

implicits include retroactively adding a method to a class, without extending


and re-compiling that class. Or, given a type signature used in some context,
automatically selecting the right implementation for that context. This is just
the tip of the iceberg—we even wrote a research paper attempting to catalog
the multitude of ways in which developers have used implicits.2
This is like providing a user with knobs and levers and leaving it to them
to build a smoothly-functioning piece of machinery, like the mechanical cal-
culator shown in Figure 1. But often, what comes out instead is something
that looks more like a kinetic sculpture of Theo Jansen, such as the one
shown in Figure 2, than anything with an obvious use.3 Simply put, you
give a programming community something as basic as a lever and a knob,
and the intrepid will seek to find creative ways to use it. It’s human nature.
But perhaps here, Scala 2’s mistake was the idea to provide something as
general-purpose as something like knobs and levers in the first place.
The point here is that in Scala 2, there was this endless array of pos-
sibilities for what implicits could be used for, which necessitated an entire
research paper, and which the community generally couldn’t agree upon how
to sanely use. No language feature should have such a murky purpose for be-
ing. And yet, here they were—implicits were seen by many as the unique
and powerful feature of Scala that essentially no other language had, and
by many others as a mysterious and often frustrating mechanism that would
invasively rewrite code that you had written to be something else.
Prepared for 138040

2 Krikava, et al., Scala implicits are everywhere. [Kri19]


3 For a more dynamic depiction of the kinetic sculptures of Theo Jansen, which are col-
lectively entitled Strandbeest, see https://www.youtube.com/watch?v=LewVEF2B_pM.

Cover · Overview · Contents · Suggest · Glossary · Index


Foreword xxxii

You may have heard the oft-repeated mantra that in many ways, Scala
3 represents a simplification of the Scala that came before it. The story of
implicits is an excellent example. Cognizant of the back flips programmers
were doing with implicits in an attempt to realize broader programming pat-
terns like typeclass derivation, Martin, with the help of many others, came
to the conclusion that we should not focus on implicits as a mechanism for
people to use in the most general case. Rather, we should focus on what
programmers want to do with implicits, and make that easier and more per-
formant. This is where the mantra, “Scala 3 focuses on intent rather than
mechanism,” comes from.
With Scala 3, rather than focus on the generality of implicits as a mech-
anism, the decision was made to focus on specific use-cases that developers
had in mind when choosing to use implicits in the first place, and to make
these patterns more direct to use. Examples include passing context or con-
figuration information to methods implicitly, without the programmer having
to explicitly thread through repetitive arguments; retroactively adding meth-
ods to classes; and converting between types, like Ints and Doubles during
arithmetic. Now, Scala 3 makes these use cases available to programmers
without needing to understand some “deep” intuition about how the Scala
compiler resolves implicits. You can instead just focus on tasks like “add a
method foo to class Bar without having to recompile it.” No PhD required.
Just replace the previous notion of “implicit” with other more direct key-
words that correspond to specific use cases, such as given and using. See
Chapters 21 and 22 for more on this.
This story of “prioritizing intent over mechanism” doesn’t stop at the
revamping of implicits. Rather, the philosophy goes on to touch upon most
every aspect of the language. Examples include additions and streamlining
of many aspects of Scala’s type system, from union types, to enums, to match
types—or even the cleanups to Scala’s syntax: optional braces to improve
readability, and more readable “quiet” syntax for ifs, elses, and whiles,
resulting in conditionals that look much more English-like.
Don’t take my word for it. Whether you’re a newcomer to Scala, or an
experienced Scala developer, I hope you find many of the new design ideas
that have entered Scala 3 to be as refreshing and straightforward as I do!
Prepared for 138040

Heather Miller
Lausanne, Switzerland
June 1, 2021

Cover · Overview · Contents · Suggest · Glossary · Index


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, Vin-
cent Cremet, Gilles Dubochet, Burak Emir, Stéphane Micheloud, Nikolay
Mihaylov, Michel Schinz, Erik Stenman, and Matthias Zenger. Phil Bag-
well, Antonio Cunei, Iulian Dragos, Gilles Dubochet, Miguel Garcia, Philipp
Haller, Sean McDirmid, Ingo Maier, Donna Malayeri, Adriaan Moors, Hu-
bert 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 Cham-
bers, 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 doc-
ument. 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
Prepared for 138040

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 · Suggest · Glossary · Index


Acknowledgments xxxiv

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 con-
tributed 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 con-
tributed 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 Hen-
ricson, 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 Borde-
lon, Alexandre Patry, Filip Moens, Fred Janon, Jeff Heon, Boris Lorbeer,
Jim Menard, Tim Azzopardi, Thomas Jung, Walter Chang, Jeroen Dijkmei-
jer, Casey Bowman, Martin Smith, Richard Dallaway, Antony Stubbs, Lars
Westergren, Maarten Hazewinkel, Matt Russell, Remigiusz Michalowski,
Andrew Tolopko, Curtis Stanford, Joshua Cough, Zemian Deng, Christo-
pher 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 Gerassi-
mov, Cameron Taggart, Jon-Anders Teigen, Silvestre Zabala, Will McQueen,
and Sam Owen.
Prepared for 138040

We would also like to thank those who submitted comments and er-
rata after the first two editions were published, including Felix Siegrist,
Lothar Meyer-Lerbs, Diethard Michaelis, Roshan Dawrani, Donn Stephan,
Cover · Overview · Contents · Suggest · Glossary · Index
Acknowledgments xxxv

William Uther, Francisco Reverbel, Jim Balter, and Freek de Bruijn, Am-
brose Laing, Sekhar Prabhala, Levon Saldamli, Andrew Bursavich, Hjal-
mar Peters, Thomas Fehr, Alain O’Dea, Rob Dickens, Tim Taylor, Chris-
tian Sternagel, Michel Parisien, Joel Neely, Brian McKeon, Thomas Fehr,
Joseph Elliott, Gabriel da Silva Ribeiro, Thomas Fehr, Pablo Ripolles, Dou-
glas Gaylor, Kevin Squire, Harry-Anton Talvik, Christopher Simpkins, Mar-
tin 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 our Stairway to Scala course, which
is in great part based on this book. Our many years of experience teaching
Stairway to Scala 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.
Finally, we would like to thank Julien Richard-Foy for his work to bring
the fourth edition of this book up to date with Scala 2.13, in particular the
new collections redesign.
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction

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

Who should read this book


The 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
you’re a Java programmer, for example, reading this book will expose you
to many concepts from functional programming as well as advanced object-
oriented 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 fine first
programming language, this is not the book to use to learn programming.
On the other hand, no specific 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 book


Prepared for 138040

Because the main purpose of this book is to serve as a tutorial, the recom-
mended way to read this book is in chapter order, from front to back. We

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction xxxvii

have tried hard to introduce one topic at a time, and explain new topics only
in terms of topics we’ve already introduced. Thus, if you skip to the back
to get an early peek at something, you may find it explained in terms of
concepts you don’t quite understand. To the extent you read the chapters
in order, we think you’ll find 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 fine.
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 specification of the Scala language, but the lan-
guage specification tries for precision at the expense of readability. Although
this book doesn’t 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.

How to learn Scala


You 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 in-
cluded 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-specific
article feeds. Take some time to find ones that fit your information needs.
You will spend a lot less time stuck on little problems, so you can 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
Prepared for 138040

larger program. You can only go so far by reading.

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction xxxviii

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, 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
val res0: Int = 7
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction xxxix

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 ba-


sic 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 pro-
gramming tasks that will help you get up to speed quickly in Scala.
After completing this chapter, you should be able to start using 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 in-
structions on how to compile and run a Scala application.

• Chapter 5, “Basic Types and Operations,” covers Scala’s basic types,


their literals, the operations you can perform on them, how 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 funda-
Prepared for 138040

mental as those in Chapter 4, but they frequently arise in practice.

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction xl

• Chapter 11, “Traits,” covers Scala’s mechanism for mixin composi-


tion. The chapter shows how traits work, describes common uses, and
explains how traits improve on traditional multiple inheritance.

• Chapter 12, “Packages and Imports,” discusses issues with program-


ming in the large, including top-level packages, import statements, and
access control modifiers like protected and private.

• Chapter 13, “Pattern Matching,” introduces twin constructs that sup-


port you when writing regular, non-encapsulated data structures. Case
classes and pattern matching are particularly helpful for tree-like re-
cursive data.

• Chapter 19, “Enums and ADTs,” introduces twin constructs that sup-
port you when writing regular, non-encapsulated data structures.

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

• Chapter 15, “Working with Other Collections,” shows you how to use
the basic Scala collections, such as lists, arrays, tuples, sets, and maps.

• Chapter 16, “Mutable Objects,” explains mutable objects and the syn-
tax Scala provides to express them. The chapter concludes with a case
study on discrete event simulation, which shows some mutable objects
in action.

• Chapter 17, “Scala’s Hierarchy,” explains Scala’s inheritance hierar-


chy and discusses its universal methods and bottom types.

• Chapter 18, “Type Parameterization,” explains some of the techniques


for information hiding introduced in Chapter 13 by means of a con-
crete 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 mem-


bers that Scala supports; not only methods, but also fields and types,
Prepared for 138040

can be declared abstract.

Cover · Overview · Contents · Suggest · Glossary · Index


Introduction xli

• Chapter 21, “Givens,” describes Scala’s feature that helps you work
with contextual parameters to functions. Passing in all contextual in-
formation is simple, but can entail a lot of boilerplate. Givens help you
reduce that boilerplate.
• Chapter 22, “Extension Methods,” describes Scala’s mechanism for
making it appear as if a function is defined as a method on a class,
when it is really defined outside the class.
• Chapter 23, “Typeclasses,” yet to be written, this chapter will illustrate
several examples of typeclasses.
• Chapter 24, “Collections in Depth,” gives a detailed tour of the collec-
tions library.
• Chapter 25, “Assertions and Tests,” shows Scala’s assertion mecha-
nism and gives a tour of several tools available for writing tests in
Scala, focusing on ScalaTest in particular.

Resources
At https://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 web-
site: https://booksites.artima.com/programming_in_scala_5ed.

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:
https://booksites.artima.com/programming_in_scala_5ed.

Errata
Although this book has been heavily reviewed and checked, errors will in-
evitably slip through. For a (hopefully short) list of errata for this book, visit
Prepared for 138040

https://booksites.artima.com/programming_in_scala_5ed/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.
Cover · Overview · Contents · Suggest · Glossary · Index
Programming in Scala
Fifth Edition

println("Hello, reader!")
Prepared for 138040

Cover · Overview · Contents · Suggest · Glossary · Index


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 and JavaScript
platforms and interoperates seamlessly with all platform libraries. It’s quite
a good language for writing scripts that pull together existing libraries. 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 program-
ming 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
Prepared for 138040

chapter you should have a basic feel for what Scala is and what kinds of
1 Scala is pronounced skah-lah.

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.1 Chapter 1 · A Scalable Language 44

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.

1.1 A language that grows on you


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

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

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

println(capital("France"))

This program sets up a map from countries to their capitals, modifies the map
by adding a new binding ("Japan" -> "Tokyo"), and prints the capital asso-
ciated with the country France.2 The notation in this example is high level, 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 leg-
ible 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 implemen-
tation, such as a HashMap or a TreeMap, or with Scala’s parallel collections
module, 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 over-
ride 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.
Prepared for 138040

2 Pleasebear with us if you don’t understand all the details of this program. They will be
explained in the next two chapters.

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.1 Chapter 1 · A Scalable Language 45

This example shows that Scala can give you both convenience and flex-
ibility. 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 al-
ways 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 soft-
ware 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
Raymond’s work the bazaar is a metaphor for open-source software devel-
opment. Guy Steele noted in a talk on “growing a language” that the 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.
Here’s an example. Many applications need a type of integer that can
become arbitrarily large without overflow or “wrap-around” of arithmetic
operations. Scala defines such a type in library class scala.math.BigInt.
Here is the definition of a method using that type, which calculates the fac-
torial of a passed integer value:5

def factorial(x: BigInt): BigInt =


if x == 0 then 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 that
3 Raymond, The Cathedral and the Bazaar. [Ray99]
Prepared for 138040

4 Steele,“Growing a language.” [Ste99]


5 factorial(x), or x! in mathematical notation, is the result of computing

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

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.1 Chapter 1 · A Scalable Language 46

happens to be defined in Scala’s standard library.6 If the class were missing,


it would be straightforward for any Scala programmer to write an implemen-
tation, for instance, by wrapping Java’s class java.math.BigInteger (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

def factorial(x: BigInteger): BigInteger =


if x == BigInteger.ZERO then
BigInteger.ONE
else
x.multiply(factorial(x.subtract(BigInteger.ONE)))

BigInt is representative of many other number-like types—big decimals,


complex numbers, rational numbers, confidence intervals, polynomials—the
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 sim-
ply 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.

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
the AnyFunSuite style of ScalaTest, a popular testing library for Scala.
As an example, here is a simple test class that contains two tests:
Prepared for 138040

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

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.2 Chapter 1 · A Scalable Language 47

class SetSpec extends AnyFunSuite:

test("An empty Set should have size 0") {


assert(Set.empty.size == 0)
}

test("Invoking head on an empty Set should fail") {


assertThrows[NoSuchElementException] {
Set.empty.head
}
}

We don’t expect you to fully understand the AnyFunSuite example at


this point. Rather, what’s significant about this example for the topic of
scalability is that neither the test construct nor the assertThrows syntax
are built-in operations in Scala. Even though the both may look and act very
much like a built-in control constructs, they are in fact methods defined in
the ScalaTest library. Both of these constructs are completely independent
of the Scala programming language.
This example illustrates that you can “grow” the Scala language in new
directions even as specialized as software testing. To be sure, you need expe-
rienced 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.

1.2 What makes Scala scalable?


Scalability is influenced by many factors, ranging from syntax details to
component abstraction constructs. If we were forced to name just one as-
pect of Scala that helps scalability, though, we’d pick its combination of
object-oriented and functional programming (well, we cheated, that’s really
two aspects, but they are intertwined).
Scala goes further than all other well-known languages in fusing object-
oriented and functional programming into a uniform language design. For
instance, where other languages might have objects and functions as two
Prepared for 138040

different concepts, in Scala a function value is an object. Function types are


classes that can be inherited by subclasses. This might seem nothing more
than an academic nicety, but it has deep consequences for scalability. This

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.2 Chapter 1 · A Scalable Language 48

section gives an overview of Scala’s way of blending object-oriented and


functional concepts.

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 sim-
ple: 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 val-
ues 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 pro-
gramming 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.
Prepared for 138040

Scala is more advanced than most other languages when it comes to com-
posing objects. An example is Scala’s traits. Traits are like interfaces in Java,
7 Kay, “The Early History of Smalltalk.” [Kay96]

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.2 Chapter 1 · A Scalable Language 49

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 as-
pects 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 clas-
sical “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 pro-
gramming 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 re-
cent 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 func-
tions as arguments to other functions, return them as results from functions,
or store them in variables. You can also define a function inside 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 ab-
stracting over operations and creating new control structures. This general-
ization 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 eventually construct
Prepared for 138040

that takes a function as an argument. It is used like this:


8 Starting with Java 8, interfaces can have default method implementations, but these do

not offer all the features of Scala’s traits.

Cover · Overview · Contents · Suggest · Glossary · Index


Section 1.2 Chapter 1 · A Scalable Language 50

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.
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 math-
ematical 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 in-
stance, 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 occur-
rences of one character are replaced by the other. There is no other effect of
calling replace. 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 referen-
tially transparent methods. Some functional languages even require them.
Scala gives you a choice. When you want to, you can write in an imper-
Prepared for 138040

ative 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.

Cover · Overview · Contents · Suggest · Glossary · Index


Discovering Diverse Content Through
Random Scribd Documents
of the same year (1817) he paid a visit to his friend, Benjamin
Bailey, at Oxford, and in November he finished Endymion at Burford
Bridge, near Dorking. His youngest brother had developed
consumption, and in March John went to Teignmouth to nurse him in
place of his brother George, who had decided to sail for America
with his newly married wife, Georgiana Wylie. In May (1818) Keats
returned to London, and soon after appeared Endymion: A Poetic
Romance (1818), bearing on the title-page as motto “The stretched
metre of an antique song.” Late in June Keats and his friend
Armitage Brown started on a walking tour in Scotland, vividly
described in the poet’s letters. The fatigue and hardship involved
proved too great a strain for Keats, who was forbidden by an
Inverness doctor to continue his tour. He returned to London by
boat, arriving on the 18th of August. The autumn was spent in
constant attendance on his brother Tom, who died at the beginning
of December. There is no doubt that he resented the attacks on him
in Blackwood’s Magazine (August 1818), and the Quarterly Review
(April 1818, published only in September), but his chief
preoccupations were elsewhere. After his brother’s death he went to
live with his friend Brown. He had already made the acquaintance of
Fanny Brawne, a girl of seventeen, who lived with her mother close
by. For her Keats quickly developed a consuming passion. He was in
indifferent health, and, owing partly to Mr Abbey’s mismanagement,
in difficulties for money. Nevertheless his best work belongs to this
period. In July 1819 he went to Shanklin, living with James Rice.
They were soon joined by Brown. The next two months Keats spent
with Brown at Winchester, enjoying an interval of calmness due to
his absence from Fanny Brawne. At Winchester he completed Lamia
and Otho the Great, which he had begun in conjunction with Brown,
and began his historical tragedy of King Stephen. Before Christmas
he had returned to London and his bondage to Fanny. In January
1820 his brother George paid a short visit to London, but received
no confidence from him. The fatal nature of Keats’s illness showed
itself on the 3rd of February, but in March he recovered sufficiently
to be present at the private view of Haydon’s picture of “Christ’s
Entry into Jerusalem.” In May he removed to a lodging in Wesleyan
Place, Kentish Town, to be near Leigh Hunt who eventually took him
into his house. In July appeared his third and last book, Lamia,
Isabella, The Eve of St Agnes and other Poems (1820). Keats left the
Hunts abruptly in August in consequence of a delay in receiving one
of Fanny Brawne’s letters which had been broken open by a servant.
He went to Wentworth Place, where he was taken in by the
Brawnes. The suggestion that he should spend the winter in Italy
was followed up by an invitation from Shelley to Pisa. This, however,
he refused. But on the 18th of September 1820 he set out for Naples
in company with Joseph Severn, the artist, who had long been his
friend. The travellers settled in the Piazza de Spagna, Rome. Keats
was devotedly tended by Dr (afterwards Sir) James Clarke and
Severn, and died on the 23rd of February 1821. He was buried on
the 27th in the old Protestant cemetery, near the pyramid of Cestius.

Bibliography.—Keats’s friends provided the material for the


authoritative biography of the poet by Richard Monckton Milnes
(afterwards Lord Houghton) entitled Life, Letters and Literary
Remains of John Keats (1848; revised ed., 1867). The Poetical
Works of John Keats were issued with a memoir by R. M. Milnes
in 1854, 1863, 1865, 1866, 1867, and in the Aldine edition,
1876. The standard edition of Keats is The Poetical Works and
other Writings of John Keats now first brought together,
including Poems and numerous Letters not before published,
edited with notes and appendices by Harry Buxton Forman (4
vols., 1883; re-issue with corrections and additions, 1889). Of
the many other editions of Keats’s poems may be mentioned
that in the Muses’ Library, The Poems of John Keats (1896),
edited by G. Thorn Drury with an introduction by Robert Bridges,
and another by E. de Sélincourt, 1905. The Letters of John Keats
to Fanny Brawne (1889) were edited with introduction and notes
by H. Buxton Forman, and the Letters of John Keats to his
Family and Friends (1891) by Sidney Colvin, who is also the
author of the monograph, Keats (1887), in the English Men of
Letters Series. See also The Papers of a Critic. Selected from the
Writings of the late Charles Wentworth Dilke (1875), and for
further bibliographical information and particulars of MS. sources
the “Editor’s Preface,” &c. to a reprint edited by H. Buxton
Forman (Glasgow, 1900). A facsimile of Keats’s autograph MS. of
“Hyperion,” purchased by the British Museum in 1904, was
published by E. de Sélincourt (Oxford, 1905). (M. Br.)

KEBLE, JOHN (1792-1866), English poet and divine, the


author of the Christian Year, was born on St Mark’s Day (April 25),
1792, at Fairford, Gloucestershire. He was the second child of the
Rev. John Keble and his wife Sarah Maule. Descended from a family
which had attained some legal eminence in the time of the
Commonwealth, John Keble, the father of the poet, was vicar of Coln
St Aldwyn, but lived at Fairford, about 3 m. distant from his cure. He
was a clergyman of the old High Church school, whose adherents,
untouched by the influence of the Wesleys, had moulded their piety
on the doctrines on the non-jurors and the old Anglican divines.
Himself a good scholar, he did not send his son to any school, but
educated him and his brother at home so well that both obtained
scholarships at Corpus Christi College, Oxford. John was elected
scholar of Corpus in his fifteenth, and fellow of Oriel in his
nineteenth year, April 1811. In Easter term 1810 he had obtained
double first class honours, a distinction which had been obtained
only once before, by Sir Robert Peel. After his election to the Oriel
fellowship Keble gained the University prizes, both for the English
essay and also for the Latin essay. But he was more remarkable for
the rare beauty of his character than even for academic distinctions.
Sir John Taylor Coleridge, his fellow scholar at Corpus and his life-
long friend, says of him, after their friendship of five and fifty years
had closed, “It was the singular happiness of his nature, remarkable
even in his undergraduate days, that love for him was always
sanctified by reverence—reverence that did not make the love less
tender, and love that did but add intensity to the reverence.” Oriel
College was, at the time when Keble became a fellow, the centre of
all the finest ability in Oxford. Copleston, Davison, Whately, were
among the fellows who elected Keble; Arnold, Pusey, Newman, were
soon after added to the society. In 1815 Keble was ordained deacon,
and priest in 1816. His real bent and choice were towards a pastoral
cure in a country parish; but he remained in Oxford, acting first as a
public examiner in the schools, then as a tutor in Oriel, till 1823. In
summer he sometimes took clerical work, sometimes made tours on
foot through various English counties, during which he was
composing poems, which afterwards took their place in the Christian
Year. He had a rare power of attracting to himself the finest spirits, a
power which lay not so much in his ability or his genius as in his
character, so simple, so humble, so pure, so unworldly, yet wanting
not that severity which can stand by principle and maintain what he
holds to be the truth. In 1823 he returned to Fairford, there to assist
his father, and with his brother to serve one or two small and poorly
endowed curacies in the neighbourhood of Coln. He had made a
quiet but deep impression on all who came within his influence in
Oxford, and during his five years of college tutorship had won the
affection of his pupils. But it was to pastoral work, and not to
academic duty, that he thenceforth devoted himself, associating with
it, and scarcely placing on a lower level, the affectionate discharge
of his duties as a son and brother. Filial piety influenced in a quite
unusual degree his feelings and his action all life through. It was in
1827, a few years after he settled at Fairford, that he published the
Christian Year. The poems which make up that book had been the
silent gathering of years. Keble had purposed in his own mind to
keep them beside him, correcting and improving them, as long as he
lived, and to leave them to be published only “when he was fairly
out of the way.” This resolution was at length overcome by the
importunities of his friends, and above all by the strong desire of his
father to see his son’s poems in print before he died. Accordingly
they were printed in two small volumes in Oxford, and given to the
world in June 1827, but with no name on the title-page. The book
continued to be published anonymously, but the name of the author
soon transpired.

Between 1827 and 1872 one hundred and fifty-eight editions had
issued from the press, and it has been largely reprinted since. The
author, so far from taking pride in his widespread reputation,
seemed all his life long to wish to disconnect his name with the
book, and “as if he would rather it had been the work of some one
else than himself.” This feeling arose from no false modesty. It was
because he knew that in these poems he had painted his own heart,
the best part of it; and he doubted whether it was right thus to
exhibit himself, and by the revelation of only his better self, to win
the good opinion of the world.

Towards the close of 1831 Keble was elected to fill the chair of the
poetry professorship in Oxford, as successor to his friend and
admirer, Dean Milman. This chair he occupied for ten eventful years.
He delivered a series of lectures, clothed in excellent idiomatic Latin
(as was the rule), in which he expounded a theory of poetry which
was original and suggestive. He looked on poetry as a vent for
overcharged feeling, or a full imagination, or some imaginative
regret, which had not found their natural outlet in life and action.
This suggested to him a distinction between what he called primary
and secondary poets—the first employing poetry to relieve their own
hearts, the second, poetic artists, composing poetry from some
other and less impulsive motive. Of the former kind were Homer,
Lucretius, Burns, Scott; of the latter were Euripides, Dryden, Milton.
This view was set forth in an article contributed to the British Critic
in 1838 on the life of Scott, and was more fully developed in two
volumes of Praelectiones Academicae.

His regular visits to Oxford kept him in intercourse with his old
friends in Oriel common room, and made him familiar with the
currents of feeling which swayed the university. Catholic
emancipation and the Reform Bill had deeply stirred, not only the
political spirit of Oxford, but also the church feeling which had long
been stagnant. Cardinal Newman writes, “On Sunday July 14, 1833,
Mr Keble preached the assize sermon in the University pulpit. It was
published under the title of National Apostasy. I have ever
considered and kept the day as the start of the religious movement
of 1833.” The occasion of this sermon was the suppression, by Earl
Grey’s Reform ministry, of ten Irish bishoprics. Against the spirit
which would treat the church as the mere creature of the state Keble
had long chafed inwardly, and now he made his outward protest,
asserting the claim of the church to a heavenly origin and a divine
prerogative. About the same time, and partly stimulated by Keble’s
sermon, some leading spirits in Oxford and elsewhere began a
concerted and systematic course of action to revive High Church
principles and the ancient patristic theology, and by these means
both to defend the church against the assaults of its enemies, and
also to raise to a higher tone the standard of Christian life in
England. This design embodied itself in the Tractarian movement, a
name it received from the famous Tracts for the Times, which were
the vehicle for promulgating the new doctrines. If Keble is to be
reckoned, as Newman would have it, as the primary author of the
movement, it was from Pusey that it received one of its best known
names, and in Newman that it soon found its genuine leader. To the
tracts Keble made only four contributions:—No. 4, containing an
argument, in the manner of Bishop Butler, to show that adherence to
apostolical succession is the safest course; No. 13, which explains
the principle on which the Sunday lessons in the church service are
selected; No. 40, on marriage with one who is unbaptized; No. 89,
on the mysticism attributed to the early fathers of the church.
Besides these contributions from his own pen, he did much for the
series by suggesting subjects, by reviewing tracts written by others,
and by lending to their circulation the weight of his personal
influence.

In 1835 Keble’s father died at the age of ninety, and soon after
this his son married Miss Clarke, left Fairford, and settled at Hursley
vicarage in Hampshire, a living to which he had been presented by
his friend and attached pupil, Sir William Heathcote, and which
continued to be Keble’s home and cure for the remainder of his life.

In 1841 the tracts were brought to an abrupt termination by the


publication of Newman’s tract No. 90. All the Protestantism of
England was in arms against the author of the obnoxious tract. Keble
came forward at the time, desirous to share the responsibility and
the blame, if there was any; for he had seen the tract before it was
published, and approved it. The same year in which burst this
ecclesiastical storm saw the close of Keble’s tenure of the
professorship of poetry, and thenceforward he was seen but rarely in
Oxford. No other public event ever affected Keble so deeply as the
secession of Newman to the Church of Rome in 1845. It was to him
both a public and a private sorrow, which nothing could repair. But
he did not lose heart; at once he threw himself into the double duty,
which now devolved on himself and Pusey, of counselling the many
who had hitherto followed the movement, and who, now in their
perplexity, might be tempted to follow their leader’s example, and at
the same time of maintaining the rights of the church against what
he held to be the encroachments of the state, as seen in such acts
as the Gorham judgment, and the decision on Essays and Reviews.
In all the ecclesiastical contests of the twenty years which followed
1845, Keble took a part, not loud or obtrusive, but firm and resolute,
in maintaining those High Anglican principles with which his life had
been identified. These absorbing duties, added to his parochial work,
left little time for literature. But in 1846 he published the Lyra
Innocentium; and in 1863 he completed a life of Bishop Wilson.

In the late autumn of the latter year, Keble left Hursley for the
sake of his wife’s health, and sought the milder climate of
Bournemouth. There he had an attack of paralysis, from which he
died on the 29th of March 1866. He was buried in his own
churchyard at Hursley; and in little more than a month his wife was
laid by her husband’s side.

Keble also published A Metrical Version of the Psalter (1839),


Lyra Innocentium (1846), and a volume of poems was published
posthumously. But it is by the Christian Year that he won the ear
of the religious world. It was a happy thought that dictated the
plan of the book, to furnish a meditative religious lyric for each
Sunday of the year, and for each saint’s day and festival of the
English Church. The subject of each poem is generally
suggested by some part of the lessons or the gospel or the
epistle for the day. One thing which gives these poems their
strangely unique power is the sentiment to which they appeal,
and the saintly character of the poet who makes the appeal,
illumining more or less every poem.

The intimacy with the Bible which is manifest in the pages of


the Christian Year; and the unobtrusive felicity with which
Biblical sentiments and language are introduced have done
much to endear these poems to all Bible readers. “The
exactness of the descriptions of Palestine, which Keble had
never visited, have been noted, and verified on the spot,” by
Dean Stanley. He points to features of the lake of Gennesareth,
which were first touched in the Christian Year; and he observes
that throughout the book “the Biblical scenery is treated
graphically as real scenery, and the Biblical history and poetry as
real history and poetry.”

As to its style, the Christian Year is calm and grave in tone,


and subdued in colour, as beseems its subjects and sentiments.
The contemporary poets whom Keble most admired were Scott,
Wordsworth and Southey; and of their influence traces are
visible in his diction. Yet he has a style of language and a
cadence of his own, which steal into the heart with strangely
soothing power. Some of the poems are faultless, after their
kind, flowing from the first stage to the last, lucid in thought,
vivid in diction, harmonious in their pensive melody. In others
there are imperfections in rhythm, conventionalities of language,
obscurities or over-subtleties of thought, which mar the reader’s
enjoyment. Yet even the most defective poems commonly have,
at least, a single verse, expressing some profound thought or
tender shade of feeling, for which the sympathetic reader
willingly pardons artistic imperfections in the rest.

Keble’s life was written by his life-long friend Mr Justice J. T.


Coleridge. The following is a complete list of his writings:—1.
Works published in Keble’s lifetime: Christian Year (1827);
Psalter (1839); Praelectiones Academicae (1844); Lyra
Innocentium (1846); Sermons Academical (1848); Argument
against Repeal of Marriage Law, and Sequel (1857);
Eucharistical Adoration (1857); Life of Bishop Wilson (1863);
Sermons Occasional and Parochial (1867). 2. Posthumous
publications: Village Sermons on the Baptismal Service (1868);
Miscellaneous Poems (1869); Letters of Spiritual Counsel (1870);
Sermons for the Christian Year, &c. (11 vols., 1875-1880);
Occasional Papers and Reviews (1877); Studia Sacra (1877);
Outlines of Instruction or Meditation (1880).
KECSKEMÉT, a town of Hungary, in the county of Pest-Pilis-
Solt-Kiskun, 65 m. S.S.E. of Budapest by rail. Pop. (1900), 56,786.
Kecskemét is a poorly built and straggling town, situated in the
extensive Kecskemét plain. It contains monasteries belonging to the
Piarist and Franciscan orders, a Catholic (founded in 1714), a
Calvinistic and a Lutheran school. The manufacture of soap and
leather are the principal industries. Besides the raising of cereals,
fruit is extensively cultivated in the surrounding district; its apples
and apricots are largely exported, large quantities of wine are
produced, and cattle-rearing constitutes another great source of
revenue. Kecskemét was the birthplace of the Hungarian dramatist
József Katona (1792-1830), author of the historical drama, Bánk-Bán
(1815).

KEDDAH (from Hindu Khedna, to chase), the term, used in


India for the enclosure constructed to entrap elephants. In Ceylon
the word employed in the same meaning is corral.
KEDGEREE (Hindostani, khichri), an Indian dish, composed of
boiled rice and various highly-flavoured ingredients. Kedgeree is of
two kinds, white and yellow. The white is made with grain, onions,
ghee (clarified butter), cloves, pepper and salt. Yellow kedgeree
includes eggs, and is coloured by turmeric. Kedgeree is a favourite
and universal dish in India; among the poorer classes it is frequently
made of rice and pulse only, or rice and beans. In European cookery
kedgeree is a similar dish usually made with fish.

KEEL, the bottom timber or combination of plates of a ship or


boat, extending longitudinally from bow to stern, and supporting the
framework (see Ship-building). The origin of the word has been
obscured by confusion of two words, the Old Norwegian kjole (cf.
Swedish köl) and a Dutch and German kiel. The first had the
meaning of the English “keel,” the other of ship, boat. The modern
usage in Dutch and German has approximated to the English. The
word kiel is represented in old English by céol, a word applied to the
long war galleys of the Vikings, in which sense “keel” or “keele” is
still used by archaeologists. On the Tyne “keel” is the name given to
a flat-bottomed vessel used to carry coals to the colliers. There is
another word “keel,” meaning to cool, familiar in Shakespeare
(Love’s Labour Lost, v. ii. 930), “while greasy Joan doth keel the
pot,” i.e. prevents a pot from boiling over by pouring in cold water,
&c., stirring or skimming. This is from the Old English célan, to cool,
a common Teutonic word, cf. German kühlen.

KEELEY, MARY ANNE (1806-1899), English actress, was


born at Ipswich on the 22nd of November 1805 or 1806. Her maiden
name was Goward, her father being a brazier and tinman. After
some experience in the provinces, she first appeared on the stage in
London on the 2nd of July 1825, in the opera Rosina. It was not long
before she gave up “singing parts” in favour of the drama proper,
where her powers of character-acting could have scope. In June
1829 she married Robert Keeley (1793-1869), an admirable
comedian, with whom she had often appeared. Between 1832 and
1842 they acted at Covent Garden, at the Adelphi with Buckstone, at
the Olympic with Charles Mathews, and at Drury Lane with
Macready. In 1836 they visited America. In 1838 she made her first
great success as Nydia, the blind girl, in a dramatized version of
Bulwer Lytton’s The Last Days of Pompeii, and followed this with an
equally striking impersonation of Smike in Nicholas Nickleby. In 1839
came her decisive triumph with her picturesque and spirited acting
as the hero of a play founded upon Harrison Ainsworth’s Jack
Sheppard. So dangerous was considered the popularity of the play,
with its glorification of the prison-breaking felon, that the lord
chamberlain ultimately forbade the performance of any piece upon
the subject. It is perhaps mainly as Jack Sheppard that Mrs Keeley
lived in the memory of playgoers, despite her long subsequent
career in plays more worthy of her remarkable gifts. Under
Macready’s management she played Nerissa in The Merchant of
Venice, and Audrey in As You Like It. She managed the Lyceum with
her husband from 1844 to 1847; acted with Webster and Kean at
the Haymarket; returned for five years to the Adelphi; and made her
last regular public appearance at the Lyceum in 1859. A public
reception was given her at this theatre on her 90th birthday. She
died on the 12th of March 1899.

See Walter Goodman, The Keeleys on the Stage and off


(London, 1895).

KEELING ISLANDS (often called Cocos and Cocos-Keeling


Islands), a group of coral islands in the Indian Ocean, between 12°
4′ and 12° 13′ S., and 96° 49′-57′ E., but including a smaller island
in 11° 50′ N. and 96° 50′ E. The group furnished Charles Darwin
with the typical example of an atoll or lagoon island. There are
altogether twenty-three small islands, 9½ m. being the greatest
width of the whole atoll. The lagoon is very shallow and the
passages between many of the islands are fordable on foot. An
opening on the northern side of the reef permits the entrance of
vessels into the northern part of the lagoon, which forms a good
harbour known as Port Refuge or Port Albion. The coco-nut (as the
name Cocos Islands indicates) is the characteristic product and is
cultivated on all the islands. The flora is scanty in species. One of
the commonest living creatures is a monstrous crab which lives on
the coco-nuts; and in some places also there are great colonies of
the pomegranate crab. The group was visited by Dr H. O. Forbes in
1878, and later, at the expense of Sir John Murray, by Dr Guppy, Mr
Ridley and Dr Andrews. The object of their visits was the
investigation of the fauna and flora of the atoll, more especially of
the formation of the coral reefs. Dr Guppy was fortunate in reaching
North Keeling Island, where a landing is only possible during the
calmest weather. The island he found to be about a mile long, with a
shallow enclosed lagoon, less than 3 ft. deep at ordinary low water,
with a single opening on its east or weather side. A dense vegetation
of iron-wood (Cordia) and other trees and shrubs, together with a
forest of coco-nut palms, covers its surface. It is tenanted by
myriads of sea-fowl, frigate-birds, boobies, and terns (Gygis
candida), which find here an excellent nesting-place, for the island is
uninhabited, and is visited only once or twice a year. The excrement
from this large colony has changed the carbonate of lime in the soil
and the coral nodules on the surface into phosphates, to the extent
in some cases of 60-70%, thus forming a valuable deposit, beneficial
to the vegetation of the island itself and promising commercial value.
The lagoon is slowly filling up and becoming cultivable land, but the
rate of recovery from the sea has been specially marked since the
eruption of Krakatoa, the pumice from which was washed on to it in
enormous quantity, so that the lagoon advanced its shores from 20
to 30 yards. Forbes’s and Guppy’s investigations go to show that,
contrary to Darwin’s belief, there is no evidence of upheaval or of
subsidence in either of the Keeling groups.

The atoll has an exceedingly healthy climate, and might well be


used as a sanatorium for phthisical patients, the temperature never
reaching extremes. The highest annual reading of the thermometer
hardly ever exceeds 89° F. or falls beneath 70°. The mean
temperature for the year is 78.5° F., and as the rainfall rarely
exceeds 40 in. the atmosphere never becomes unpleasantly moist.
The south-east trade blows almost ceaselessly for ten months of the
year. Terrific storms sometimes break over the island; and it has
been more than once visited by earthquakes. A profitable trade is
done in coco-nuts, but there are few other exports. The imports are
almost entirely foodstuffs and other necessaries for the inhabitants,
who form a patriarchal colony under a private proprietor.

The islands were discovered in 1609 by Captain William Keeling on


his voyage from Batavia to the Cape. In 1823 Alexander Hare, an
English adventurer, settled on the southernmost island with a
number of slaves. Some two or three years after, a Scotchman, J.
Ross, who had commanded a brig during the English occupation of
Java, settled with his family (who continued in the ownership) on
Direction Island, and his little colony was soon strengthened by
Hare’s runaway slaves. The Dutch Government had in an informal
way claimed the possession of the islands since 1829; but they
refused to allow Ross to hoist the Dutch flag, and accordingly the
group was taken under British protection in 1856. In 1878 it was
attached to the government of Ceylon, and in 1882 placed under the
authority of the governor of the Straits Settlements. The ownership
and superintendency continued in the Ross family, of whom George
Clunies Ross died in 1910, and was succeeded by his son Sydney.

See C. Darwin, Journal of the Voyage of the “Beagle,” and


Geological Observations on Coral Reefs; also Henry O. Forbes, A
Naturalist’s Wanderings in the Eastern Archipelago (London,
1884); H. B. Guppy, “The Cocos-Keeling Islands,” Scottish
Geographical Magazine (vol. v., 1889).

KEEL-MOULDING, in architecture, a round on which there


is a small fillet, somewhat like the keel of a ship. It is common in the
Early English and Decorated styles.

KEENE, CHARLES SAMUEL (1823-1891), English black-


and-white artist, the son of Samuel Browne Keene, a solicitor, was
born at Hornsey on the 10th of August 1823. Educated at the
Ipswich Grammar School until his sixteenth year, he early showed
artistic leanings. Two years after the death of his father he was
articled to a London solicitor, but, the occupation proving
uncongenial, he was removed to the office of an architect, Mr
Pilkington. His spare time was now spent in drawing historical and
nautical subjects in water-colour. For these trifles his mother, to
whose energy and common sense he was greatly indebted, soon
found a purchaser, through whom he was brought to the notice of
the Whympers, the wood-engravers. This led to his being bound to
them as apprentice for five years. His earliest known design is the
frontispiece, signed “Chas. Keene,” to The Adventures of Dick
Boldhero in Search of his Uncle, &c. (Darton & Co., 1842). His term
of apprenticeship over, he hired as studio an attic in the block of
buildings standing, up to 1900, between the Strand and Holywell
Street, and was soon hard at work for the Illustrated London News.
At this time he was a member of the “Artists’ Society” in Clipstone
Street, afterwards removed to the Langham studios. In December
1851 he made his first appearance in Punch and, after nine years of
steady work, was called to a seat at the famous table. It was during
this period of probation that he first gave evidence of those
transcendent qualities which make his work at once the joy and
despair of his brother craftsmen. On the starting of Once a Week, in
1859, Keene’s services were requisitioned, his most notable series in
this periodical being the illustrations to Charles Reade’s A Good Fight
(afterwards rechristened The Cloister and the Hearth) and to George
Meredith’s Evan Harrington. There is a quality of conventionality in
the earlier of these which completely disappears in the later. In 1858
Keene, who was endowed with a fine voice and was an enthusiastic
admirer of old-fashioned music, joined the “Jermyn Band,”
afterwards better known as the “Moray Minstrels.” He was also for
many years a member of Leslie’s Choir, the Sacred Harmonic Society,
the Catch, Glee and Canon Club, and the Bach Choir. He was also an
industrious performer on the bagpipes, of which instrument he
brought together a considerable collection of specimens. About 1863
the Arts Club in Hanover Square was started, with Keene as one of
the original members. In 1864 John Leech died, and Keene’s work in
Punch thenceforward found wider opportunities. It was about this
time that the greatest of all modern artists of his class, Menzel,
discovered Keene’s existence, and became a subscriber to Punch
solely for the sake of enjoying week by week the work of his brother
craftsman. In 1872 Keene, who, though fully possessed of the
humorous sense, was not within measurable distance of Leech as a
jester, and whose drawings were consequently not sufficiently
“funny” to appeal to the laughter-loving public, was fortunate
enough to make the acquaintance of Mr Joseph Crawhall, who had
been in the habit for many years of jotting down any humorous
incidents he might hear of or observe, illustrating them at leisure for
his own amusement. These were placed unreservedly at Keene’s
disposal, and to their inspiration we owe at least 250 of his most
successful drawings in the last twenty years of his connexion with
Punch. A list of more than 200 of these subjects is given at the end
of The Life and Letters of Charles Keene of “Punch.” In 1879 Keene
removed to 239 King’s Road, Chelsea, which he occupied until his
last illness, walking daily to and from his house, 112 Hammersmith
Road. In 1881 a volume of his Punch drawings was published by
Messrs Bradbury & Agnew, with the title Our People. In 1883 Keene,
who had hitherto been a strong man, developed symptoms of
dyspepsia and rheumatism. By 1889 these had increased to an
alarming degree, and the last two years of his life were passed in
acute suffering borne with the greatest courage. He died unmarried,
after a singularly uneventful life, on the 4th of January 1891, and his
body lies in Hammersmith cemetery.

Keene, who never had any regular art training, was essentially
an artists’ artist. He holds the foremost place amongst English
craftsmen in black and white, though his work has never been
appreciated at its real value by the general public. No doubt the
main reason for this lack of public recognition was his
unconventionality. He drew his models exactly as he saw them,
not as he knew the world wanted to see them. He found enough
beauty and romance in all that was around him, and, in his
Punch work, enough subtle humour in nature seized at her most
humorous moments to satisfy him. He never required his models
to grin through a horse collar, as Gillray did, or to put on their
company manners, as was du Maurier’s wont. But Keene was
not only a brilliant worker in pen and ink. As an etcher he has
also to be reckoned with, notwithstanding the fact that his plates
numbered not more than fifty at the outside. Impressions of
them are exceedingly rare, and hardly half a dozen of the plates
are now known to be in existence. He himself regarded them
only as experiments in a difficult but fascinating medium. But in
the opinion of the expert they suffice to place him among the
best etchers of the 19th century. Apart from the etched
frontispieces to some of the Punch pocket-books, only three,
and these by no means the best, have been published. Writing
in L’Artiste for May 1891 of a few which he had seen,
Bracquemond says: “By the freedom, the largeness of their
drawing and execution, these plates must be classed amongst
modern etchings of the first rank.” A few impressions are in the
British Museum, but in the main they were given away to friends
and lie hidden in the albums of the collector.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like