754
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Programming in Scala

Embed Size (px)

Citation preview

Cover Overview Contents Discuss Suggest Glossary Index

Programming in Scala

Cover Overview Contents Discuss Suggest Glossary Index

Programming in ScalaMartin Odersky, Lex Spoon, Bill Venners

artimaA RTIMA P RESSM OUNTAIN V IEW, C ALIFORNIA

Cover Overview Contents Discuss Suggest Glossary Index

ivProgramming in Scala First Edition, Version 6 Martin Odersky is the creator of the Scala language and a professor at EPFL in Lausanne, Switzerland. Lex Spoon worked on Scala for two years as a post-doc with Martin Odersky. Bill Venners is president of Artima, Inc. Artima Press is an imprint of Artima, Inc. P.O. Box 390122, Mountain View, California 94039 Copyright 2007, 2008 Martin Odersky, Lex Spoon, and Bill Venners. All rights reserved. First edition published as PrePrint eBook 2007 First edition published 2008 Produced in the United States of America 12 11 10 09 08 5 6 7 8 9 ISBN-10: 0-9815316-1-X ISBN-13: 978-0-9815316-1-8 No part of this publication may be reproduced, modied, distributed, stored in a retrieval system, republished, displayed, or performed, for commercial or noncommercial purposes or for compensation of any kind without prior written permission from Artima, Inc. All information and materials in this book are provided "as is" and without warranty of any kind. The term Artima and the Artima logo are trademarks or registered trademarks of Artima, Inc. All other company and/or product names may be trademarks or registered trademarks of their owners.

Cover Overview Contents Discuss Suggest Glossary Index

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

Cover Overview Contents Discuss Suggest Glossary Index

OverviewContents List of Figures List of Tables List of Listings Foreword Acknowledgments Introduction 1. A Scalable Language 2. First Steps in Scala 3. Next Steps in Scala 4. Classes and Objects 5. Basic Types and Operations 6. Functional Objects 7. Built-in Control Structures 8. Functions and Closures 9. Control Abstraction 10. Composition and Inheritance 11. Scalas Hierarchy 12. Traits 13. Packages and Imports 14. Assertions and Unit Testing 15. Case Classes and Pattern Matching 16. Working with Lists 17. Collections 18. Stateful Objects 19. Type Parameterization 20. Abstract Members 21. Implicit Conversions and Parameters 22. Implementing Lists 23. For Expressions Revisited 24. Extractors 25. Annotations 26. Working with XML 27. Modular Programming Using Objects 28. Object Equality 29. Combining Scala and Java 30. Actors and Concurrency 31. Combinator Parsing 32. GUI Programming 33. The SCells Spreadsheet A. Scala scripts on Unix and Windows Glossary Bibliography About the Authors Indexvii xvii xix xx xxvii xxix xxxi 39 58 71 93 107 129 149 173 194 209 237 245 264 279 293 327 359 387 410 435 465 487 500 516 532 539 553 568 594 607 642 671 683 708 709 725 728 729

Cover Overview Contents Discuss Suggest Glossary Index

Contents

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

vii xvii xix xx xxvii xxix xxxi 39 40 45 48 55 57 58 58 60 62 64 65 67 70

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

2

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

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 3 Next Steps in Scala Step 7. Parameterize arrays with types . . . . Step 8. Use lists . . . . . . . . . . . . . . . . Step 9. Use tuples . . . . . . . . . . . . . . . Step 10. Use sets and maps . . . . . . . . . . . Step 11. Learn to recognize the functional style Step 12. Read lines from a le . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . Classes and Objects 4.1 Classes, elds, and methods 4.2 Semicolon inference . . . . 4.3 Singleton objects . . . . . . 4.4 A Scala application . . . . 4.5 The Application trait . . . 4.6 Conclusion . . . . . . . . . 71 71 75 80 81 86 89 92 93 93 98 99 102 105 106 107 107 108 115 118 119 121 123 124 127 127 129 129 130 132 133 133 135 136 138

viii

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

4

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

5

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

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

6

Functional Objects 6.1 A specication for class Rational . . 6.2 Constructing a Rational . . . . . . . 6.3 Reimplementing the toString method 6.4 Checking preconditions . . . . . . . . 6.5 Adding elds . . . . . . . . . . . . . . 6.6 Self references . . . . . . . . . . . . . 6.7 Auxiliary constructors . . . . . . . . . 6.8 Private elds and methods . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 6.9 6.10 6.11 6.12 6.13 6.14 7 Dening operators . Identiers in Scala . Method overloading Implicit conversions A word of caution . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 141 144 146 147 147 149 150 151 154 159 163 165 167 170 172 173 173 175 177 179 180 181 184 188 189 193 194 194 198 200 202 205 208

ix

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

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

8

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

9

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

. . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 10 Composition and Inheritance 10.1 A two-dimensional layout library . . . . . . 10.2 Abstract classes . . . . . . . . . . . . . . . 10.3 Dening parameterless methods . . . . . . . 10.4 Extending classes . . . . . . . . . . . . . . 10.5 Overriding methods and elds . . . . . . . . 10.6 Dening parametric elds . . . . . . . . . . 10.7 Invoking superclass constructors . . . . . . . 10.8 Using override modiers . . . . . . . . . . 10.9 Polymorphism and dynamic binding . . . . 10.10 Declaring nal members . . . . . . . . . . . 10.11 Using composition and inheritance . . . . . 10.12 Implementing above, beside, and toString 10.13 Dening a factory object . . . . . . . . . . . 10.14 Heighten and widen . . . . . . . . . . . . . 10.15 Putting it all together . . . . . . . . . . . . . 10.16 Conclusion . . . . . . . . . . . . . . . . . . 11 Scalas Hierarchy 11.1 Scalas class hierarchy . . . . . . 11.2 How primitives are implemented 11.3 Bottom types . . . . . . . . . . . 11.4 Conclusion . . . . . . . . . . . . 12 Traits 12.1 How traits work . . . . . . . . . 12.2 Thin versus rich interfaces . . . . 12.3 Example: Rectangular objects . . 12.4 The Ordered trait . . . . . . . . 12.5 Traits as stackable modications . 12.6 Why not multiple inheritance? . . 12.7 To trait, or not to trait? . . . . . . 12.8 Conclusion . . . . . . . . . . . . 209 209 210 211 214 216 217 219 220 222 224 226 227 229 231 235 236 237 237 241 243 244 245 245 248 249 252 254 258 262 263 264 264 268 272

x

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

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

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

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

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

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

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

13 Packages and Imports 13.1 Packages . . . . . . . . . . . . . . . . . . . . . . . . . 13.2 Imports . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3 Implicit imports . . . . . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

Contents 13.4 Access modiers . . . . . . . . . . . . . . . . . . . . . 13.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 14 Assertions and Unit Testing 14.1 Assertions . . . . . . . . . . 14.2 Unit testing in Scala . . . . . 14.3 Informative failure reports . . 14.4 Using JUnit and TestNG . . . 14.5 Tests as specications . . . . 14.6 Property-based testing . . . . 14.7 Organizing and running tests 14.8 Conclusion . . . . . . . . . . 273 278 279 279 281 282 284 286 288 290 292 293 293 298 307 309 310 312 314 318 326 327 327 328 328 329 330 332 343 351 355 358 359 359

xi

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

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

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

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

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

17 Collections 17.1 Overview of the library . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

Contents 17.2 17.3 17.4 17.5 17.6 17.7 Sequences . . . . . . . . . . . . . . . . . . . . Sets and maps . . . . . . . . . . . . . . . . . . Selecting mutable versus immutable collections Initializing collections . . . . . . . . . . . . . . Tuples . . . . . . . . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 367 377 380 383 386 387 387 390 393 394 397 401 409 410 410 414 417 421 424 426 429 431 434 435 435 436 437 438 439 447 449 452 454 463

xii

18 Stateful Objects 18.1 What makes an object stateful? . . . 18.2 Reassignable variables and properties 18.3 Case study: Discrete event simulation 18.4 A language for digital circuits . . . . 18.5 The Simulation API . . . . . . . . 18.6 Circuit Simulation . . . . . . . . . . 18.7 Conclusion . . . . . . . . . . . . . . 19 Type Parameterization 19.1 Functional queues . . . . . . . 19.2 Information hiding . . . . . . . 19.3 Variance annotations . . . . . . 19.4 Checking variance annotations . 19.5 Lower bounds . . . . . . . . . 19.6 Contravariance . . . . . . . . . 19.7 Object private data . . . . . . . 19.8 Upper bounds . . . . . . . . . 19.9 Conclusion . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

20 Abstract Members 20.1 A quick tour of abstract members 20.2 Type members . . . . . . . . . . 20.3 Abstract vals . . . . . . . . . . . 20.4 Abstract vars . . . . . . . . . . . 20.5 Initializing abstract vals . . . . . 20.6 Abstract types . . . . . . . . . . 20.7 Path-dependent types . . . . . . 20.8 Enumerations . . . . . . . . . . . 20.9 Case study: Currencies . . . . . . 20.10 Conclusion . . . . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

. . . . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 21 Implicit Conversions and Parameters 21.1 Implicit conversions . . . . . . . . . . 21.2 Rules for implicits . . . . . . . . . . . 21.3 Implicit conversion to an expected type 21.4 Converting the receiver . . . . . . . . 21.5 Implicit parameters . . . . . . . . . . . 21.6 View bounds . . . . . . . . . . . . . . 21.7 Debugging implicits . . . . . . . . . . 21.8 Conclusion . . . . . . . . . . . . . . . 22 Implementing Lists 22.1 The List class in principle 22.2 The ListBuffer class . . . 22.3 The List class in practice . 22.4 Functional on the outside . 22.5 Conclusion . . . . . . . . . 465 465 468 471 473 475 481 485 486 487 487 493 495 497 498 500 501 503 506 508 512 513 515 516 516 517 520 522 525 526 527 531 532 532

xiii

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

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

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

24 Extractors 24.1 An example: Extracting email addresses 24.2 Extractors . . . . . . . . . . . . . . . . 24.3 Patterns with zero or one variables . . . 24.4 Variable argument extractors . . . . . . . 24.5 Extractors and sequence patterns . . . . 24.6 Extractors versus case classes . . . . . . 24.7 Regular expressions . . . . . . . . . . . 24.8 Conclusion . . . . . . . . . . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

25 Annotations 25.1 Why have annotations? . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

Contents 25.2 Syntax of annotations . . . . . . . . . . . . . . . . . . 25.3 Standard annotations . . . . . . . . . . . . . . . . . . . 25.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 26 Working with XML 26.1 Semi-structured data . . . 26.2 XML overview . . . . . . 26.3 XML literals . . . . . . . 26.4 Serialization . . . . . . . 26.5 Taking XML apart . . . . 26.6 Deserialization . . . . . . 26.7 Loading and saving . . . 26.8 Pattern matching on XML 26.9 Conclusion . . . . . . . . 533 535 537 539 539 540 541 543 545 546 547 549 552 553 554 555 558 561 564 565 567 568 568 569 582 587 593 594 594 597 602 606 607

xiv

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

27 Modular Programming Using Objects 27.1 The problem . . . . . . . . . . . 27.2 A recipe application . . . . . . . 27.3 Abstraction . . . . . . . . . . . . 27.4 Splitting modules into traits . . . 27.5 Runtime linking . . . . . . . . . 27.6 Tracking module instances . . . . 27.7 Conclusion . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

28 Object Equality 28.1 Equality in Scala . . . . . . . . . . . . . 28.2 Writing an equality method . . . . . . . 28.3 Dening equality for parameterized types 28.4 Recipes for equals and hashCode . . . 28.5 Conclusion . . . . . . . . . . . . . . . . 29 Combining Scala and Java 29.1 Using Scala from Java 29.2 Annotations . . . . . 29.3 Existential types . . . 29.4 Conclusion . . . . . . 30 Actors and Concurrency

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents 30.1 30.2 30.3 30.4 30.5 30.6 30.7 Trouble in paradise . . . . . . . . . . . . . . . . . . Actors and message passing . . . . . . . . . . . . . Treating native threads as actors . . . . . . . . . . . Better performance through thread reuse . . . . . . Good actors style . . . . . . . . . . . . . . . . . . . A longer example: Parallel discrete event simulation Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607 608 612 613 616 623 640 642 643 645 646 647 649 655 664 665 665 667 669 671 671 674 676 679 681 683 683 686 689 691 696 699 702 706

xv

31 Combinator Parsing 31.1 Example: Arithmetic expressions . . 31.2 Running your parser . . . . . . . . . 31.3 Basic regular expression parsers . . . 31.4 Another example: JSON . . . . . . . 31.5 Parser output . . . . . . . . . . . . . 31.6 Implementing combinator parsers . . 31.7 String literals and regular expressions 31.8 Lexing and parsing . . . . . . . . . . 31.9 Error reporting . . . . . . . . . . . . 31.10 Backtracking versus LL(1) . . . . . . 31.11 Conclusion . . . . . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

. . . . . . . . . . .

32 GUI Programming 32.1 A rst Swing application . . . . . . . . 32.2 Panels and layouts . . . . . . . . . . . 32.3 Handling events . . . . . . . . . . . . 32.4 Example: Celsius/Fahrenheit converter 32.5 Conclusion . . . . . . . . . . . . . . . 33 The SCells Spreadsheet 33.1 The visual framework . . . . . . . . 33.2 Disconnecting data entry and display 33.3 Formulas . . . . . . . . . . . . . . . 33.4 Parsing formulas . . . . . . . . . . . 33.5 Evaluation . . . . . . . . . . . . . . 33.6 Operation libraries . . . . . . . . . . 33.7 Change propagation . . . . . . . . . 33.8 Conclusion . . . . . . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

. . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

Contents A Scala scripts on Unix and Windows Glossary Bibliography About the Authors Index 708 709 725 728 729

xvi

Cover Overview Contents Discuss Suggest Glossary Index

List of Figures2.1 2.2 3.1 3.2 3.3 10.1 10.2 10.3 10.4 The basic form of a function denition in Scala. . . . . . . . The syntax of a function literal in Scala. . . . . . . . . . . . All operations are method calls in Scala. . . . . . . . . . . . Class hierarchy for Scala sets. . . . . . . . . . . . . . . . . Class hierarchy for Scala maps. . . . . . . . . . . . . . . . . Class diagram for ArrayElement. . . . . . Class diagram for LineElement. . . . . . . Class hierarchy of layout elements . . . . . Class hierarchy with revised LineElement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 69 74 82 84 215 220 223 227 239 261 291 360 361 394 396 397 429 488 492

11.1 Class hierarchy of Scala. . . . . . . . . . . . . . . . . . . . 12.1 Inheritance hierarchy and linearization of class Cat. . . . . . 14.1 ScalaTests graphical reporter. . . . . . . . . . . . . . . . . 17.1 Class hierarchy for Scala collections. . . . . . . . . . . . . . 17.2 Class hierarchy for Iterator. . . . . . . . . . . . . . . . . 18.1 Basic gates. . . . . . . . . . . . . . . . . . . . . . . . . . . 18.2 A half-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 18.3 A full-adder circuit. . . . . . . . . . . . . . . . . . . . . . . 19.1 Covariance and contravariance in function type parameters. . 22.1 Class hierarchy for Scala lists. . . . . . . . . . . . . . . . . 22.2 The structure of the Scala lists shown in Listing 22.2. . . . .

xvii

List of Figures 32.1 A simple Swing application: initial (left) and resized (right). 32.2 A reactive Swing application: initial (left) after clicks (right). 32.3 A converter between degrees Celsius and Fahrenheit. . . . . 33.1 33.2 33.3 33.4 A simple spreadsheet table. . . Cells displaying themselves. . Cells displaying their formulas. Cells that evaluate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 674 679 684 689 695 701

xviii

Cover Overview Contents Discuss Suggest Glossary Index

List of Tables3.1 5.1 5.2 5.3 5.4 5.5 Some List methods and usages . . . . . . . . . . . . . . . Some basic types . . . . . . . . . . . . . Special character literal escape sequences Operator precedence . . . . . . . . . . . Some rich operations . . . . . . . . . . . Rich wrapper classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 108 112 126 128 128 262 276 330 370 372 374 374 653

12.1 Linearization of types in Cats hierarchy . . . . . . . . . . . 13.1 Effects of private qualiers on LegOfJourney.distance . . 16.1 Basic list operations . . . . . . . . . . . . . . . . . . . . . . 17.1 17.2 17.3 17.4 Common operations for sets . . . . . . . Common operations for maps . . . . . . . Default immutable set implementations . Default immutable map implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31.1 Summary of parser combinators . . . . . . . . . . . . . . .

xix

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

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

72 75 76 80 81 83 84 85 87 89 92 97 100 102 105 135 137 138 140 145 150 151 152 153 154

. . . . . . . . .

. . . . . . . . .

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

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

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

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

xxi 156 156 157 158 159 161 162 163 164 164 166 166 168 171 174 176 198 201 201 205 206 211 212 214 216 218 219 225 225 230 231 232 233 234 235

Using closures to reduce code duplication. . Dening and invoking a plain old function. Dening and invoking a curried function. . . Using the loan pattern to write to a le. . . . Using a by-name parameter. . . . . . . . . .

. . . . .

. . . . .

. . . . .

. . . . .

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

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

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

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

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

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 12.1 12.2 12.3 12.4 12.5 12.6 12.7 12.8 12.9 12.10 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 13.12 14.1 14.2 14.3 14.4 14.5 14.6 14.7 14.8 14.9 14.10 15.1 15.2 15.3 The denition of trait Philosophical. . . . . . . . . . . . Mixing in a trait using extends. . . . . . . . . . . . . . . Mixing in a trait using with. . . . . . . . . . . . . . . . . Mixing in multiple traits. . . . . . . . . . . . . . . . . . . Dening an enrichment trait. . . . . . . . . . . . . . . . . Abstract class IntQueue. . . . . . . . . . . . . . . . . . . A BasicIntQueue implemented with an ArrayBuffer. . . The Doubling stackable modication trait. . . . . . . . . . Mixing in a trait when instantiating with new. . . . . . . . . Stackable modication traits Incrementing and Filtering. Placing the contents of an entire le into a package. . . . . Nesting multiple packages in the same le. . . . . . . . . . Nesting packages with minimal indentation. . . . . . . . . Scala packages truly nest. . . . . . . . . . . . . . . . . . . Accessing hidden package names. . . . . . . . . . . . . . . Bobs delightful fruits, ready for import. . . . . . . . . . . Importing the members of a regular (not singleton) object. . Importing a package name. . . . . . . . . . . . . . . . . . How private access differs in Scala and Java. . . . . . . . . How protected access differs in Scala and Java. . . . . . . . Flexible scope of protection with access qualiers. . . . . . Accessing private members of companion classes and objects. Using an assertion. . . . . . . . . . . . . . . . . . . . . . . Using ensuring to assert a functions result. . . . . . . . . Writing a test method with Suite. . . . . . . . . . . . . . Writing a test function with FunSuite. . . . . . . . . . . . Writing a JUnit test with JUnit3Suite. . . . . . . . . . . Writing a TestNG test with TestNGSuite. . . . . . . . . . Specifying and testing behavior with a ScalaTest Spec. . . Specifying and testing behavior with the specs framework. . Writing property-based tests with ScalaCheck. . . . . . . . Checking properties from a JUnit TestCase with Checkers. Dening case classes. . . . . . . . . . . . . . . . . . . . . The simplifyTop function, which does a pattern match. . . A pattern match with an empty default case. . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index 245 246 247 247 251 255 255 256 257 257 265 265 266 267 267 268 269 270 273 274 275 277 280 280 281 282 285 286 287 288 289 290 294 296 297

xxii

List of Listings 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 15.13 15.14 15.15 15.16 15.17 15.18 15.19 15.20 15.21 15.22 16.1 17.1 17.2 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10 18.11 19.1 19.2 A pattern match with wildcard patterns. . . . . . . . . . A pattern match with constant patterns. . . . . . . . . . A pattern match with a variable pattern. . . . . . . . . . A pattern match with a constructor pattern. . . . . . . . A sequence pattern with a xed length. . . . . . . . . . A sequence pattern with an arbitrary length. . . . . . . A pattern match with a tuple pattern. . . . . . . . . . . A pattern match with typed patterns. . . . . . . . . . . Using isInstanceOf and asInstanceOf (poor style). . A pattern with a variable binding (via the @ sign). . . . A match expression with a pattern guard. . . . . . . . . Match expression in which case order matters. . . . . . A sealed hierarchy of case classes. . . . . . . . . . . . Dening multiple variables with one assignment. . . . . A for expression with a tuple pattern. . . . . . . . . . Picking elements of a list that match a pattern. . . . . . The top half of the expression formatter. . . . . . . . . The bottom half of the expression formatter. . . . . . . An application that prints formatted expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 299 300 302 302 303 303 303 305 307 308 309 311 314 318 318 321 322 325 342 368 376 388 390 391 391 392 395 396 398 402 403 407 413 414

xxiii

A merge sort function for Lists. . . . . . . . . . . . . . . Default map and set denitions in Predef. . . . . . . . . . Mixing in the SynchronizedMap trait. . . . . . . . . . . . A mutable bank account class. . . . . . . . . . . . . . . . . A class with public vars. . . . . . . . . . . . . . . . . . . How public vars are expanded into getter and setter methods. Dening getter and setter methods directly. . . . . . . . . . Dening a getter and setter without an associated eld. . . The halfAdder method. . . . . . . . . . . . . . . . . . . . The fullAdder method. . . . . . . . . . . . . . . . . . . . The Simulation class. . . . . . . . . . . . . . . . . . . . The rst half of the BasicCircuitSimulation class. . . . The second half of the BasicCircuitSimulation class. . The CircuitSimulation class. . . . . . . . . . . . . . . . A basic functional queue. . . . . . . . . . . . . . . . . . . Hiding a primary constructor by making it private. . . . . . Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 19.3 19.4 19.5 19.6 19.7 19.8 19.9 19.10 19.11 19.12 20.1 20.2 20.3 20.4 20.5 20.6 20.7 20.8 20.9 20.10 20.11 20.12 20.13 20.14 21.1 21.2 21.3 21.4 21.5 21.6 21.7 22.1 22.2 22.3 22.4 An apply factory method in a companion object. . . Type abstraction for functional queues. . . . . . . . A nonvariant (rigid) Cell class. . . . . . . . . . . . A type parameter with a lower bound. . . . . . . . . A contravariant output channel. . . . . . . . . . . . Covariance and contravariance of Function1s. . . . Demonstration of function type parameter variance. An optimized functional queue. . . . . . . . . . . . A Person class that mixes in the Ordered trait. . . A merge sort function with an upper bound. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 416 419 425 426 427 428 430 432 432 438 438 439 440 442 442 443 444 448 449 459 460 461 462 477 479 480 482 483 484 484 489 491 491 493

xxiv

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

An implicit parameter list with multiple parameters. . . . . A function with an upper bound. . . . . . . . . . . . . . . A function with an implicit parameter. . . . . . . . . . . . A function that uses an implicit parameter internally. . . . . A function with a view bound. . . . . . . . . . . . . . . . . Sample code that uses an implicit parameter. . . . . . . . . Sample code after type checking and insertion of implicits. The denition of the Nil singleton object. . . . . Prepending a supertype element to a subtype list. . The denition of method :: (cons) in class List. The denition of method ::: in class List. . . . . . . . . . . . . . . . . . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 22.5 22.6 24.1 24.2 24.3 24.4 24.5 24.6 24.7 27.1 27.2 27.3 27.4 27.5 27.6 27.7 27.8 27.9 27.10 27.11 27.12 27.13 27.14 27.15 27.16 27.17 28.1 28.2 28.3 28.4 28.5 29.1 30.1 30.2 The denition of method map in class List. . . . . . . . . The denition of the :: subclass of List. . . . . . . . . . The EMail string extractor object. . . . . . . . . . The Twice string extractor object. . . . . . . . . . The UpperCase string extractor object. . . . . . . The Domain string extractor object. . . . . . . . . The ExpandedEMail extractor object. . . . . . . . Hiding a primary constructor by making it private. How the r method is dened in RichString. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495 496 518 521 521 523 524 525 529 555 556 556 557 558 559 560 560 561 561 562 562 562 562 563 564 566 580 581 583 587 588 599 609 611

xxv

A simple Food entity class. . . . . . . . . . . . . . . . . . Simple Recipe entity class. . . . . . . . . . . . . . . . . . Food and Recipe examples for use in tests. . . . . . . . . . Mock database and browser modules. . . . . . . . . . . . . Database and browser modules with categories added. . . . A Browser class with an abstract database val. . . . . . . A Database class with abstract methods. . . . . . . . . . . The SimpleDatabase object as a Database subclass. . . . The SimpleBrowser object as a Browser subclass. . . . . A student database and browser. . . . . . . . . . . . . . . . A trait for food categories. . . . . . . . . . . . . . . . . . . A Database class that mixes in the FoodCategories trait. A SimpleDatabase object composed solely of mixins. . . A SimpleFoods trait. . . . . . . . . . . . . . . . . . . . . A SimpleRecipes trait with a self type. . . . . . . . . . . An app that dynamically selects a module implementation. Using a singleton type. . . . . . . . . . . . . . . . . . . . A superclass equals method that calls canEqual. A subclass equals method that calls canEqual. . Hierarchy for binary trees. . . . . . . . . . . . . . A parameterized type with equals and hashCode. Class Rational with equals and hashCode. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A Scala method that declares a Java throws clause. . . . . A simple actor. . . . . . . . . . . . . . . . . . . . . . . . . An actor that calls receive. . . . . . . . . . . . . . . . . . Cover Overview Contents Discuss Suggest Glossary Index

List of Listings 30.3 30.4 30.5 30.6 30.7 30.8 31.1 31.2 31.3 31.4 31.5 31.6 32.1 32.2 32.3 32.4 33.1 33.2 33.3 33.4 33.5 33.6 33.7 33.8 33.9 An actor that calls react. . . . . . . . . . . . . . . . . An actors act method that uses loop. . . . . . . . . . An actor that uses a helper actor to avoid blocking itself. An actor that uses case classes for messages. . . . . . . The Simulant trait. . . . . . . . . . . . . . . . . . . . Adder components. . . . . . . . . . . . . . . . . . . . An arithmetic expression parser. . . . . . . . . . . A regular expression parser for Java identiers. . . Data in JSON format. . . . . . . . . . . . . . . . A simple JSON parser. . . . . . . . . . . . . . . . A full JSON parser that returns meaningful results. The ~ combinator method. . . . . . . . . . . . . . A simple Swing application in Scala. . . . . . . Component assembly on a panel. . . . . . . . . Implementing a reactive Swing application. . . . An implementation of the temperature converter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615 616 618 623 631 638 644 646 648 648 653 661 672 674 678 680 685 686 687 688 690 694 697 699 705

xxvi

Code for spreadsheet in Figure 33.1. . . . . . . . . The main program for the spreadsheet application. . A spreadsheet with a rendererComponent method. First version of the Model class. . . . . . . . . . . . Classes representing formulas. . . . . . . . . . . . A spreadsheet that parses formulas. . . . . . . . . . The evaluate method of trait Evaluator. . . . . . A library for arithmetic operations. . . . . . . . . . The nished spreadsheet component. . . . . . . . .

Cover Overview Contents Discuss Suggest Glossary Index

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

Foreword Will Scala be the next great language? Only time will tell. Martin Oderskys team certainly has the taste and skill for the job. One thing is sure: Scala sets a new standard against which future languages will be measured. Neal Gafter San Jose, California September 3, 2008

xxviii

Cover Overview Contents Discuss Suggest Glossary Index

AcknowledgmentsMany people have contributed to this book and to the material it covers. We are grateful to all of them. Scala itself has been a collective effort of many people. The design and the implementation of version 1.0 was helped by Philippe Altherr, Vincent Cremet, Gilles Dubochet, Burak Emir, Stphane Micheloud, Nikolay Mihaylov, Michel Schinz, Erik Stenman, and Matthias Zenger. Iulian Dragos, Gilles Dubochet, Philipp Haller, Sean McDirmid, Ingo Maier, and Adriaan Moors joined in the effort to develop the second and current version of the language and tools. Gilad Bracha, Craig Chambers, Erik Ernst, Matthias Felleisen, Shriram Krishnamurti, Gary Leavens, Sebastian Maneth, Erik Meijer, David Pollak, Jon Pretty, Klaus Ostermann, Didier Rmy, Vijay Saraswat, Don Syme, Mads Torgersen, Philip Wadler, Jamie Webb, and John Williams have shaped the design of the language by graciously sharing their ideas with us in lively and inspiring discussions, as well as through comments on previous versions of this document. The contributors to the Scala mailing list have also given very useful feedback that helped us improve the language and its tools. George Berger has worked tremendously to make the build process and the web presence for the book work smoothly. As a result this project has been delightfully free of technical snafus. Many people gave us valuable feedback on early versions of the text. Thanks goes to Eric Armstrong, George Berger, Alex Blewitt, Gilad Bracha, William Cook, Bruce Eckel, Stphane Micheloud, Todd Millstein, David Pollak, Frank Sommers, Philip Wadler, and Matthias Zenger. Thanks also to the Silicon Valley Patterns group for their very helpful review: Dave Astels, Tracy Bialik, John Brewer, Andrew Chase, Bradford Cross, Raoul Duke, John P. Eurich, Steven Ganz, Phil Goodwin, Ralph Jocham, Yan-Fa Li, Tao Ma, Jeffery Miller, Suresh Pai, Russ Rufer, Dave W. Smith, Scott Turnquest, Cover Overview Contents Discuss Suggest Glossary Index

Acknowledgments Walter Vannini, Darlene Wallach, and Jonathan Andrew Wolter. And wed like to thank Dewayne Johnson and Kim Leedy for their help with the cover art, and Frank Sommers for his work on the index. Wed also like to extend a special thanks to all of our readers who contributed comments. Your comments were very helpful to us in shaping this into an even better book. We couldnt print the names of everyone who contributed comments, but here are the names of readers who submitted at least ve comments during the eBook PrePrint stage by clicking on the Suggest link, sorted rst by the highest total number of comments submitted, then alphabetically. Thanks goes to: David Biesack, Donn Stephan, Mats Henricson, Rob Dickens, Blair Zajac, Tony Sloane, Nigel Harrison, Javier Diaz Soto, William Heelan, Justin Forder, Gregor Purdy, Colin Perkins, Bjarte S. Karlsen, Ervin Varga, Eric Willigers, Mark Hayes, Martin Elwin, Calum MacLean, Jonathan Wolter, Les Pruszynski, Seth Tisue, Andrei Formiga, Dmitry Grigoriev, George Berger, Howard Lovatt, John P. Eurich, Marius Scurtescu, Jeff Ervin, Jamie Webb, Kurt Zoglmann, Dean Wampler, Nikolaj Lindberg, Peter McLain, Arkadiusz Stryjski, Shanky Surana, Craig Bordelon, Alexandre Patry, Filip Moens, Fred Janon, Jeff Heon, Boris Lorbeer, Jim Menard, Tim Azzopardi, Thomas Jung, Walter Chang, Jeroen Dijkmeijer, Casey Bowman, Martin Smith, Richard Dallaway, Antony Stubbs, Lars Westergren, Maarten Hazewinkel, Matt Russell, Remigiusz Michalowski, Andrew Tolopko, Curtis Stanford, Joshua Cough, Zemian Deng, Christopher Rodrigues Macias, Juan Miguel Garcia Lopez, Michel Schinz, Peter Moore, Randolph Kahle, Vladimir Kelman, Daniel Gronau, Dirk Detering, Hiroaki Nakamura, Ole Hougaard, Bhaskar Maddala, David Bernard, Derek Mahar, George Kollias, Kristian Nordal, Normen Mueller, Rafael Ferreira, Binil Thomas, John Nilsson, Jorge Ortiz, Marcus Schulte, Vadim Gerassimov, Cameron Taggart, Jon-Anders Teigen, Silvestre Zabala, Will McQueen, and Sam Owen. Lastly, Bill would also like to thank Gary Cornell, Greg Doench, Andy Hunt, Mike Leonard, Tyler Ortman, Bill Pollock, Dave Thomas, and Adam Wright for providing insight and advice on book publishing.

xxx

Cover Overview Contents Discuss Suggest Glossary Index

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

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

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

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

xxxii

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

Cover Overview Contents Discuss Suggest Glossary Index

Introduction

xxxiii

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

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

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

Cover Overview Contents Discuss Suggest Glossary Index

Introduction

xxxiv

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

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

xxxv

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

xxxvi

Introduction

xxxvii

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

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

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

Cover Overview Contents Discuss Suggest Glossary Index

Programming in Scalaprintln("Hello, reader!")

Cover Overview Contents Discuss Suggest Glossary Index

Chapter 1

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

is pronounced skah-lah.

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language tasks it might help you accomplish. Although this book is a Scala tutorial, this chapter isnt really part of the tutorial. If youre eager to start writing some Scala code, you should jump ahead to Chapter 2.

40

1.1

A language that grows on you

Programs of different sizes tend to require different programming constructs. Consider, for example, the following small Scala program:var capital = Map("US" -> "Washington", "France" -> "Paris") capital += ("Japan" -> "Tokyo") println(capital("France"))

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

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language This example shows that Scala can give you both convenience and exibility. Scala has a set of convenient constructs that help you get started quickly and let you program in a pleasantly concise style. At the same time, you have the assurance that you will not outgrow the language. You can always tailor the program to your requirements, because everything is based on library modules that you can select and adapt as needed. Growing new types Eric Raymond introduced the cathedral and bazaar as two metaphors of software development.3 The cathedral is a near-perfect building that takes a long time to build. Once built, it stays unchanged for a long time. The bazaar, by contrast, is adapted and extended each day by the people working in it. In Raymonds work the bazaar is a metaphor for open-source software development. Guy Steele noted in a talk on growing a language that the same distinction can be applied to language design.4 Scala is much more like a bazaar than a cathedral, in the sense that it is designed to be extended and adapted by the people programming in it. Instead of providing all constructs you might ever need in one perfectly complete language, Scala puts the tools for building such constructs into your hands. Heres an example. Many applications need a type of integer that can become arbitrarily large without overow or wrap-around of arithmetic operations. Scala denes such a type in library class scala.BigInt. Here is the denition of a method using that type, which calculates the factorial of a passed integer value:5def factorial(x: BigInt): BigInt = if (x == 0) 1 else x * factorial(x - 1)

41

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 thatPrepared for tetsu soh

The Cathedral and the Bazaar. [Ray99] Growing a language. [Ste99] 5 factorial(x), or x! in mathematical notation, is the result of computing 1 * 2 * ... * x, with 0! dened to be 1.4 Steele,

3 Raymond,

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language happens to be dened in Scalas standard library.6 If the class were missing, it would be straightforward for any Scala programmer to write an implementation, for instance, by wrapping Javas class java.math.BigInteger (in fact thats how Scalas BigInt class is implemented). Of course, you could also use Javas class directly. But the result is not nearly as pleasant, because although Java allows you to create new types, those types dont feel much like native language support:import java.math.BigInteger def factorial(x: BigInteger): BigInteger = if (x == BigInteger.ZERO) BigInteger.ONE else x.multiply(factorial(x.subtract(BigInteger.ONE)))

42

BigInt is representative of many other number-like typesbig decimals, complex numbers, rational numbers, condence intervals, polynomialsthe list goes on. Some programming languages implement some of these types natively. For instance, Lisp, Haskell, and Python implement big integers; Fortran and Python implement complex numbers. But any language that attempted to implement all of these abstractions at the same time would simply become too big to be manageable. Whats more, even if such a language were to exist, some applications would surely benet from other numberlike types that were not supplied. So the approach of attempting to provide everything in one language doesnt scale very well. Instead, Scala allows users to grow and adapt the language in the directions they need by dening easy-to-use libraries that feel like native language support.

Growing new control constructs The previous example demonstrates that Scala lets you add new types that can be used as conveniently as built-in types. The same extension principle also applies to control structures. This kind of extensibility is illustrated by Scalas API for actor-based concurrent programming.6 Scala comes with a standard library, some of which will be covered in this book. For more information, you can also consult the librarys Scaladoc documentation, which is available in the distribution and online at http://www.scala-lang.org.

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language As multicore processors proliferate in the coming years, achieving acceptable performance may increasingly require that you exploit more parallelism in your applications. Often, this will mean rewriting your code so that computations are distributed over several concurrent threads. Unfortunately, creating dependable multi-threaded applications has proven challenging in practice. Javas threading model is built around shared memory and locking, a model that is often difcult to reason about, especially as systems scale up in size and complexity. It is hard to be sure you dont have a race condition or deadlock lurkingsomething that didnt show up during testing, but might just show up in production. An arguably safer alternative is a message passing architecture such as the actors approach used by the Erlang programming language. Java comes with a rich, thread-based concurrency library. Scala programs can use it like any other Java API. However, Scala also offers an additional library that essentially implements Erlangs actor model. Actors are concurrency abstractions that can be implemented on top of threads. They communicate by sending messages to each other. An actor can perform two basic operations, message send and receive. The send operation, denoted by an exclamation point (!), sends a message to an actor. Heres an example in which the actor is named recipient:recipient ! msg

43

A send is asynchronous; that is, the sending actor can proceed immediately, without waiting for the message to be received and processed. Every actor has a mailbox in which incoming messages are queued. An actor handles messages that have arrived in its mailbox via a receive block:receive { case Msg1 => ... // handle Msg1 case Msg2 => ... // handle Msg2 // ... }

A receive block consists of a number of cases that each query the mailbox with a message pattern. The rst message in the mailbox that matches any of the cases is selected, and the corresponding action is performed on it. If the mailbox does not contain any messages that match one of the given cases, the actor suspends and waits for further incoming messages. Cover Overview Contents Discuss Suggest Glossary Index

Section 1.1

Chapter 1 A Scalable Language As an example, here is a simple Scala actor implementing a checksum calculator service:actor { var sum = 0 loop { receive { case Data(bytes) } } } => sum += hash(bytes) case GetSum(requester) => requester ! sum

44

This actor rst denes a local variable named sum with initial value zero. It then repeatedly waits in a loop for messages, using a receive statement. If it receives a Data message, it adds a hash of the sent bytes to the sum variable. If it receives a GetSum message, it sends the current value of sum back to the requester using the message send requester ! sum. The requester eld is embedded in the GetSum message; it usually refers to the actor that made the request. We dont expect you to understand fully the actor example at this point. Rather, whats signicant about this example for the topic of scalability is that neither actor nor loop nor receive nor message send (!) are built-in operations in Scala. Even though actor, loop, and receive look and act very much like built-in control constructs such as while or for loops, they are in fact methods dened in Scalas actors library. Likewise, even though ! looks like a built-in operator, it too is just a method dened in the actors library. All four of these constructs are completely independent of the Scala programming language. The receive block and send (!) syntax look in Scala much like they look in Erlang, but in Erlang, these constructs are built into the language. Scala also implements most of Erlangs other concurrent programming constructs, such as monitoring failed actors and time-outs. All in all, actors have turned out to be a very pleasant means for expressing concurrent and distributed computations. Even though they are dened in a library, actors feel like an integral part of the Scala language. This example illustrates that you can grow the Scala language in new directions even as specialized as concurrent programming. To be sure, you need good architects and programmers to do this. But the crucial thing is Cover Overview Contents Discuss Suggest Glossary Index

Section 1.2

Chapter 1 A Scalable Language that it is feasibleyou can design and implement abstractions in Scala that address radically new application domains, yet still feel like native language support.

45

1.2

What makes Scala scalable?

Scalability is inuenced by many factors, ranging from syntax details to component abstraction constructs. If we were forced to name just one aspect of Scala that helps scalability, though, wed pick its combination of object-oriented and functional programming (well, we cheated, thats really two aspects, but they are intertwined). Scala goes further than all other well-known languages in fusing objectoriented and functional programming into a uniform language design. For instance, where other languages might have objects and functions as two 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. In fact the actor concept shown previously could not have been implemented without this unication of functions and objects. This section gives an overview of Scalas 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 denition of what object-oriented means, there is clearly something about objects that appeals to programmers. In principle, the motivation for object-oriented programming is very simple: all but the most trivial programs need some sort of structure. The most straightforward way to do this is to put data and operations into some form of containers. The great idea of object-oriented programming is to make these containers fully general, so that they can contain operations as well as data, and that they are themselves values that can be stored in other containers, or passed as parameters to operations. Such containers are called objects. Alan Kay, the inventor of Smalltalk, remarked that in this way the simplest object has the same construction principle as a full computer: it combines data with Cover Overview Contents Discuss Suggest Glossary Index

Section 1.2

Chapter 1 A Scalable Language operations under a formalized interface.7 So objects have a lot to do with language scalability: the same techniques apply to the construction of small as well as large programs. Even though object-oriented programming has been mainstream for a long time, there are relatively few languages that have followed Smalltalk in pushing this construction principle to its logical conclusion. For instance, many languages admit values that are not objects, such as the primitive values in Java. Or they allow static elds and methods that are not members of any object. These deviations from the pure idea of object-oriented programming look quite harmless at rst, 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 + dened in class Int. You can dene methods with operator-like names that clients of your API can then use in operator notation. This is how the designer of Scalas actors API enabled you to use expressions such as requester ! sum shown in the previous example: ! is a method of the Actor class. Scala is more advanced than most other languages when it comes to composing objects. An example is Scalas traits. Traits are like interfaces in Java, but they can also have method implementations and even elds. Objects are constructed by mixin composition, which takes the members of a class and adds the members of a number of traits to them. In this way, different aspects of classes can be encapsulated in different traits. This looks a bit like multiple inheritance, but differs when it comes to the details. Unlike a class, a trait can add some new functionality to an unspecied superclass. This makes traits more pluggable than classes. In particular, it avoids the classical diamond inheritance problems of multiple inheritance, which arise when the same class is inherited via several different paths. Scala is functional In addition to being a pure object-oriented language, Scala is also a fullblown functional language. The ideas of functional programming are older than (electronic) computers. Their foundation was laid in Alonzo Churchs lambda calculus, which he developed in the 1930s. The rst functional programming language was Lisp, which dates from the late 50s. Other popular7 Kay,

46

The Early History of Smalltalk. [Kay96]

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.2

Chapter 1 A Scalable Language 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, recent years have seen an increased interest in functional programming languages and techniques. Functional programming is guided by two main ideas. The rst idea is that functions are rst-class values. In a functional language, a function is a value of the same status as, say, an integer or a string. You can pass functions as arguments to other functions, return them as results from functions, or store them in variables. You can also dene a function inside another function, just as you can dene an integer value inside a function. And you can dene 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 rst-class values provide a convenient means for abstracting over operations and creating new control structures. This generalization of functions provides great expressiveness, which often leads to very legible and concise programs. It also plays an important role for scalability. As an example, the receive construct shown previously in the actor example is an invocation of a method that takes a function as argument. The code inside the receive construct is a function that is passed unexecuted into the receive method. In most traditional languages, by contrast, functions are not values. Languages that do have function values often relegate them to second-class status. For example, the function pointers of C and C++ do not have the same status as non-functional values in those languages: function pointers can only refer to global functions, they do not allow you to dene rst-class nested functions that refer to some values in their environment. Nor do they allow you to dene unnamed function literals. The second main idea of functional programming is that the operations of a program should map input values to output values rather than change data in place. To see the difference, consider the implementation of strings in Ruby and in Java. In Ruby, a string is an array of characters. Characters in a string can be changed individually. For instance you can change a semicolon character in a string to a period inside the same string object. In Java and Scala, on the other hand, a string is a sequence of characters in the mathematical sense. Replacing a character in a string using an expression like s.replace(';', '.') yields a new string object, which is different from s. Another way of expressing this is that strings are immutable in Java Cover Overview Contents Discuss Suggest Glossary Index

47

Section 1.3

Chapter 1 A Scalable Language 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 dene many more immutable data types on top of those found in the Java APIs. For instance, Scala has immutable lists, tuples, maps, and sets. Another way of stating this second idea of functional programming is that methods should not have any side effects. They should communicate with their environment only by taking arguments and returning results. For instance, the replace method in Javas String class ts this description. It takes a string and two characters and yields a new string where all occurrences of one character are replaced by the other. There is no other effect of 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 programs semantics. Functional languages encourage immutable data structures and referentially transparent methods. Some functional languages even require them. Scala gives you a choice. When you want to, you can write in an imperative style, which is what programming with mutable data and side effects is called. But Scala generally makes it easy to avoid imperative constructs when you want, because good functional alternatives exist.

48

1.3

Why Scala?

Is Scala for you? You will have to see and decide for yourself. We have found that there are actually many reasons besides scalability to like programming in Scala. Four of the most important aspects will be discussed in this section: compatibility, brevity, high-level abstractions, and advanced static typing. Scala is compatible Scala doesnt require you to leap backwards off the Java platform to step forward from the Java language. It allows you to add value to existing codeto build on what you already havebecause it was designed for seamless interoperability with Java.8 Scala programs compile to JVM bytecodes. Their run-time performance is usually on par with Java programs. Scala code canis also a Scala variant that runs on the .NET platform, but the JVM variant currently has better support.8 There

Cover Overview Contents Discuss Suggest Glossary Index

Section 1.3

Chapter 1 A Scalable Language call Java methods, access Java elds, inherit from Java classes, and implement Java interfaces. None of this requires special syntax, explicit interface descriptions, or glue code. In fact, almost all Scala code makes heavy use of Java libraries, often without programmers being aware of this fact. Another aspect of full interoperability is that Scala heavily re-uses Java types. Scalas Ints are represented as Java primitive integers of type int, Floats are represented as floats, Booleans as booleans, and so on. Scala arrays are mapped to Java arrays. Scala also re-uses many of the standard Java library types. For instance, the type of a string literal "abc" in Scala is java.lang.String, and a thrown exception must be a subclass of java.lang.Throwable. Scala not only re-uses Javas types, but also dresses them up to make them nicer. For instance, Scalas strings support methods like toInt or toFloat, which convert the string to an integer or oating-point number. So you can write str.toInt instead of Integer.parseInt(str). How can this be achieved without breaking interoperability? Javas String class certainly has no toInt method! In fact, Scala has a very general solution to solve this tension between advanced library design and interoperability. Scala lets you dene implicit conversions, which are always applied when types would not normally match up, or when non-existing members are selected. In the case above, when looking for a toInt method on a string, the Scala compiler will nd no such member of class String, but it will nd an implicit conversion that converts a Java String to an instance of the Scala class RichString, which does dene such a member. The conversion will then be applied implicitly before performing the toInt operation. Scala code can also be invoked from Java code. This is sometimes a bit more subtle, because Scala is a richer language than Java, so some of Scalas more advanced features need to be encoded before they can be mapped to Java. Chapter 29 explains the details. Scala is concise Scala programs tend to be short. Scala programmers have reported reductions in number of lines of up to a factor of ten compared to Java. These might be extreme cases. A more conservative estimate would be that a typical Scala program should have about half the number of lines of the same program written in Java. Fewer lines of code mean not only less typing, but also less effort at reading and understanding programs and fewer possibiliCover Overview Contents Discuss Suggest Glossary Index

49

Section 1.3

Chapter 1 A Scalable Language ties of defects. There are several factors that contribute to this reduction in lines of code. First, Scalas syntax avoids some of the boilerplate that burdens Java programs. For instance, semicolons are optional in Scala and are usually left out. There are also several other areas where Scalas syntax is less noisy. As an example, compare how you write classes and constructors in Java and Scala. In Java, a class with a constructor often looks like this:// this is Java class MyClass { private int index; private String name; public MyClass(int index, String name) { this.index = index; this.name = name; } }

50

In Scala, you would likely write this instead:class MyClass(index: Int, name: String)

Given this code, the Scala compiler will produce a class that has two private instance variables, an Int named index and a String named name, and a constructor that takes initial values for those variables as parameters. Th