Programming Scala - LinuxLinks

1y ago
12 Views
2 Downloads
5.55 MB
448 Pages
Last View : 21d ago
Last Download : 3m ago
Upload by : Carlos Cepeda
Transcription

Programming Scala

Programming Scala Dean Wampler and Alex Payne Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Programming Scala by Dean Wampler and Alex Payne Copyright 2009 Dean Wampler and Alex Payne. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Mike Loukides Production Editor: Sarah Schneider Proofreader: Sarah Schneider Indexer: Ellen Troutman Zaig Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: September 2009: First Edition. O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming Scala, the image of a Malayan tapir, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This work has been released under the Creative Commons Attribution-Noncommercial license. ISBN: 978-0-596-15595-7 [M] 1252446332

To Dad and Mom, who always believed in me. To Ann, who was always there for me. —Dean To my mother, who gave me an appreciation for good writing and the accompanying intellectual tools with which to attempt to produce it. To Kristen, for her unending patience, love, and kindness. —Alex

Table of Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii 1. Zero to Sixty: Introducing Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Why Scala? If You Are a Java Programmer If You Are a Ruby, Python, etc. Programmer Introducing Scala The Seductions of Scala Installing Scala For More Information A Taste of Scala A Taste of Concurrency Recap and What’s Next 1 1 2 4 7 8 10 10 16 21 2. Type Less, Do More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 In This Chapter Semicolons Variable Declarations Method Declarations Method Default and Named Arguments (Scala Version 2.8) Nesting Method Definitions Inferring Type Information Literals Integer Literals Floating-Point Literals Boolean Literals Character Literals String Literals Symbol Literals 23 23 24 25 26 28 29 36 36 37 38 38 39 39 vii

Tuples Option, Some, and None: Avoiding nulls Organizing Code in Files and Namespaces Importing Types and Their Members Imports are Relative Abstract Types And Parameterized Types Reserved Words Recap and What’s Next 40 41 44 45 46 47 49 52 3. Rounding Out the Essentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Operator? Operator? Syntactic Sugar Methods Without Parentheses and Dots Precedence Rules Domain-Specific Languages Scala if Statements Scala for Comprehensions A Dog-Simple Example Filtering Yielding Expanded Scope Other Looping Constructs Scala while Loops Scala do-while Loops Generator Expressions Conditional Operators Pattern Matching A Simple Match Variables in Matches Matching on Type Matching on Sequences Matching on Tuples (and Guards) Matching on Case Classes Matching on Regular Expressions Binding Nested Variables in Case Clauses Using try, catch, and finally Clauses Concluding Remarks on Pattern Matching Enumerations Recap and What’s Next 53 54 55 56 57 58 59 59 60 60 61 61 61 62 62 63 63 64 64 65 65 66 67 68 69 70 71 72 74 4. Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Introducing Traits Traits As Mixins viii Table of Contents 75 76

Stackable Traits Constructing Traits Class or Trait? Recap and What’s Next 82 86 87 88 5. Basic Object-Oriented Programming in Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Class and Object Basics Parent Classes Constructors in Scala Calling Parent Class Constructors Nested Classes Visibility Rules Public Visibility Protected Visibility Private Visibility Scoped Private and Protected Visibility Final Thoughts on Visibility Recap and What’s Next 89 91 91 94 95 96 98 99 100 102 110 110 6. Advanced Object-Oriented Programming In Scala . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Overriding Members of Classes and Traits Attempting to Override final Declarations Overriding Abstract and Concrete Methods Overriding Abstract and Concrete Fields Overriding Abstract and Concrete Fields in Traits Overriding Abstract and Concrete Fields in Classes Overriding Abstract Types When Accessor Methods and Fields Are Indistinguishable: The Uniform Access Principle Companion Objects Apply Unapply Apply and UnapplySeq for Collections Companion Objects and Java Static Methods Case Classes Syntactic Sugar for Binary Operations The copy Method in Scala Version 2.8 Case Class Inheritance Equality of Objects The equals Method The and ! Methods The ne and eq Methods Array Equality and the sameElements Method 111 112 112 114 114 119 120 123 126 127 129 132 133 136 139 140 140 142 143 143 143 143 Table of Contents ix

Recap and What’s Next 144 7. The Scala Object System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 The Predef Object Classes and Objects: Where Are the Statics? Package Objects Sealed Class Hierarchies The Scala Type Hierarchy Linearization of an Object’s Hierarchy Recap and What’s Next 145 148 150 151 155 159 164 8. Functional Programming in Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 What Is Functional Programming? Functions in Mathematics Variables that Aren’t Functional Programming in Scala Function Literals and Closures Purity Inside Versus Outside Recursion Tail Calls and Tail-Call Optimization Trampoline for Tail Calls Functional Data Structures Lists in Functional Programming Maps in Functional Programming Sets in Functional Programming Other Data Structures in Functional Programming Traversing, Mapping, Filtering, Folding, and Reducing Traversal Mapping Filtering Folding and Reducing Functional Options Pattern Matching Partial Functions Currying Implicits Implicit Conversions Implicit Function Parameters Final Thoughts on Implicits Call by Name, Call by Value Lazy Vals Recap: Functional Component Abstractions x Table of Contents 165 166 166 167 169 169 170 171 172 172 173 173 174 174 174 175 175 178 179 181 182 183 184 186 186 188 189 189 190 192

9. Robust, Scalable Concurrency with Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 The Problems of Shared, Synchronized State Actors Actors in Abstract Actors in Scala Sending Messages to Actors The Mailbox Actors in Depth Effective Actors Traditional Concurrency in Scala: Threading and Events One-Off Threads Using java.util.concurrent Events Recap and What’s Next 193 193 194 194 195 196 197 202 203 203 204 204 210 10. Herding XML in Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Reading XML Exploring XML Looping and Matching XML Writing XML A Real-World Example Recap and What’s Next 211 212 213 214 215 216 11. Domain-Specific Languages in Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Internal DSLs A Payroll Internal DSL Infix Operator Notation Implicit Conversions and User-Defined Types Apply Methods Payroll Rules DSL Implementation Internal DSLs: Final Thoughts External DSLs with Parser Combinators About Parser Combinators A Payroll External DSL A Scala Implementation of the External DSL Grammar Generating Paychecks with the External DSL Internal Versus External DSLs: Final Thoughts Recap and What’s Next 218 222 223 223 224 224 229 230 230 230 233 239 244 245 12. The Scala Type System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 Reflecting on Types Understanding Parameterized Types Manifests 248 249 250 Table of Contents xi

Parameterized Methods Variance Under Inheritance Variance of Mutable Types Variance In Scala Versus Java Implementation Notes Type Bounds Upper Type Bounds Lower Type Bounds A Closer Look at Lists Views and View Bounds Nothing and Null Understanding Abstract Types Parameterized Types Versus Abstract Types Path-Dependent Types C.this C.super path.x Value Types Type Designators Tuples Parameterized Types Annotated Types Compound Types Infix Types Function Types Type Projections Singleton Types Self-Type Annotations Structural Types Existential Types Infinite Data Structures and Laziness Recap and What’s Next 251 251 255 256 259 259 259 260 261 263 267 267 270 272 273 273 274 275 275 275 275 275 276 276 277 279 279 279 283 284 285 288 13. Application Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 Annotations Enumerations Versus Pattern Matching Thoughts On Annotations and Enumerations Enumerations Versus Case Classes and Pattern Matching Using Nulls Versus Options Options and for Comprehensions Exceptions and the Alternatives Scalable Abstractions Fine-Grained Visibility Rules xii Table of Contents 289 300 304 304 306 308 311 313 314

Mixin Composition Self-Type Annotations and Abstract Type Members Effective Design of Traits Design Patterns The Visitor Pattern: A Better Alternative Dependency Injection in Scala: The Cake Pattern Better Design with Design By Contract Recap and What’s Next 316 317 321 325 326 334 340 342 14. Scala Tools, Libraries, and IDE Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Command-Line Tools scalac Command-Line Tool The scala Command-Line Tool The scalap, javap, and jad Command-Line Tools The scaladoc Command-Line Tool The sbaz Command-Line Tool The fsc Command-Line Tool Build Tools Integration with IDEs Eclipse IntelliJ NetBeans Text Editors Test-Driven Development in Scala ScalaTest Specs ScalaCheck Other Notable Scala Libraries and Tools Lift Scalaz Scalax MetaScala JavaRebel Miscellaneous Smaller Libraries Java Interoperability Java and Scala Generics Using Scala Functions in Java JavaBean Properties AnyVal Types and Java Primitives Scala Names in Java Code Java Library Interoperability AspectJ The Spring Framework 343 343 345 350 352 352 353 353 353 354 356 359 360 361 361 363 365 367 367 367 368 368 368 368 369 369 371 374 375 375 377 377 381 Table of Contents xiii

Terracotta Hadoop Recap and What’s Next 384 384 385 Appendix: References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 xiv Table of Contents

Foreword If there has been a common theme throughout my career as a programmer, it has been the quest for better abstractions and better tools to support the craft of writing software. Over the years, I have come to value one trait more than any other: composability. If one can write code with good composability, it usually means that other traits we software developers value—such as orthogonality, loose coupling, and high cohesion— are already present. It is all connected. When I discovered Scala some years ago, the thing that made the biggest impression on me was its composability. Through some very elegant design choices and simple yet powerful abstractions that were taken from the object-oriented and functional programming worlds, Martin Odersky has managed to create a language with high cohesion and orthogonal, deep abstractions that invites composability in all dimensions of software design. Scala is truly a SCAlable LAnguage that scales with usage, from scripting all the way up to large-scale enterprise applications and middleware. Scala was born out of academia, but it has grown into a pragmatic and practical language that is very much ready for real-world production use. What excites me most about this book is that it’s so practical. Dean and Alex have done a fantastic job, not only by explaining the language through interesting discussions and samples, but also by putting it in the context of the real world. Itʼs written for the programmer who wants to get things done. I had the pleasure of getting to know Dean some years ago when we were both part of the aspect-oriented programming community. Dean holds a rare mix of deep analytical academic thinking and a pragmatic, get-things-done kind of mentality. Alex, whom I’ve had the pleasure to meet once, is leading the API team at Twitter, Inc. Alex has played a leading role in moving Twitter’s code and infrastructure to Scala, making it one on the first companies to successfully deploy Scala in production. xv

You are about to learn how to write reusable components using mixin and function composition; how to write concurrent applications using Scala’s Actors; how to make effective use of Scala’s XML/XPath support; how to utilize Scalaʼs rich, flexible, and expressive syntax to build Domain-Specific Languages; how to effectively test your Scala code; how to use Scala with popular frameworks such as Spring, Hadoop, and Terracotta; and much, much more. Enjoy the ride. I sure did. —Jonas Bonér Independent Consultant, Scalable Solutions AB August, 2009 xvi Foreword

Preface Programming Scala introduces an exciting new language that offers all the benefits of a modern object model, functional programming, and an advanced type system. Packed with code examples, this comprehensive book teaches you how to be productive with Scala quickly, and explains what makes this language ideal for today’s scalable, distributed, component-based applications that support concurrency and distribution. You’ll also learn how Scala takes advantage of the advanced Java Virtual Machine as a platform for programming languages. Learn more at http://programmingscala.com or at the book’s catalog page. Welcome to Programming Scala Programming languages become popular for many reasons. Sometimes, programmers on a given platform prefer a particular language, or one is institutionalized by a vendor. Most Mac OS programmers use Objective-C. Most Windows programmers use C and .NET languages. Most embedded-systems developers use C and C . Sometimes, popularity derived from technical merit gives way to fashion and fanaticism. C , Java, and Ruby have been the objects of fanatical devotion among programmers. Sometimes, a language becomes popular because it fits the needs of its era. Java was initially seen as a perfect fit for browser-based, rich client applications. Smalltalk captured the essence of object-oriented programming (OOP) as that model of programming entered the mainstream. Today, concurrency, heterogeneity, always-on services, and ever-shrinking development schedules are driving interest in functional programming (FP). It appears that the dominance of object-oriented programming may be over. Mixing paradigms is becoming popular, even necessary. We gravitated to Scala from other languages because Scala embodies many of the optimal qualities we want in a general-purpose programming language for the kinds of applications we build today: reliable, high-performance, highly concurrent Internet and enterprise applications. xvii

Scala is a multi-paradigm language, supporting both object-oriented and functional programming approaches. Scala is scalable, suitable for everything from short scripts up to large-scale, component-based applications. Scala is sophisticated, incorporating state-of-the-art ideas from the halls of computer science departments worldwide. Yet Scala is practical. Its creator, Martin Odersky, participated in the development of Java for years and understands the needs of professional developers. Both of us were seduced by Scala, by its concise, elegant, and expressive syntax and by the breadth of tools it put at our disposal. In this book, we strive to demonstrate why all these qualities make Scala a compelling and indispensable programming language. If you are an experienced developer who wants a fast, thorough introduction to Scala, this book is for you. You may be evaluating Scala as a replacement for or complement to your current languages. Maybe you have already decided to use Scala, and you need to learn its features and how to use it well. Either way, we hope to illuminate this powerful language for you in an accessible way. We assume that you are well versed in object-oriented programming, but we don’t assume that you have prior exposure to functional programming. We assume that you are experienced in one or more other programming languages. We draw parallels to features in Java, C#, Ruby, and other languages. If you know any of these languages, we’ll point out similar features in Scala, as well as many features that are new. Whether you come from an object-oriented or functional programming background, you will see how Scala elegantly combines both paradigms, demonstrating their complementary nature. Based on many examples, you will understand how and when to apply OOP and FP techniques to many different design problems. In the end, we hope that you too will be seduced by Scala. Even if Scala does not end up becoming your day-to-day language, we hope you will gain insights that you can apply regardless of which language you are using. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, file names, and file extensions. Many italicized terms are defined in the Glossary on page 393. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. xviii Preface

Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Programming Scala by Dean Wampler and Alex Payne. Copyright 2009 Dean Wampler and Alex Payne, 978-0-596-15595-7.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Getting the Code Examples You can download the code examples from http://examples.oreilly.com/ 9780596155964/. Unzip the files to a convenient location. See the README.txt file in the distribution for instructions on building and using the examples. Some of the example files can be run as scripts using the scala command. Others must be compiled into class files. Some files contain deliberate errors and won’t compile. We have adopted a file naming convention to indicate each of these cases, although as you learn Scala it should become obvious from the contents of the files, in most cases: *-script.scala Files that end in -script.scala can be run on a command line using scala, e.g., scala foo-script.scala. You can also start scala in the interpreter mode (when you Preface xix

don’t specify a script file) and load any script file in the interpreter using the :load filename command. *-wont-compile.scala Files that end in -wont-compile.scala contain deliberate errors that will cause them to fail to compile. We use this naming convention, along with one or more embedded comments about the errors, so it will be clear that they are invalid. Also, these files are skipped by the build process for the examples. sake.scala Files named sake.scala are used by our build tool, called sake. The README.txt file describes this tool. *.scala All other Scala files must be compiled using scalac. In the distribution, they are used either by other compiled or script files, such as tests, not all of which are listed in this book. Safari Books Online Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) xx Preface

707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at: http://oreilly.com/catalog/9780596155957/ To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at: http://oreilly.com Acknowledgments As we developed this book, many people read early drafts and suggested numerous improvements to the text, for which we are eternally grateful. We are especially grateful to Steve Jensen, Ramnivas Laddad, Marcel Molina, Bill Venners, and Jonas Bonér for their extensive feedback. Much of the feedback we received came through the Safari Rough Cuts releases and the online edition available at http://programmingscala.com. We are grateful for the feedback provided by (in no particular order) Iulian Dragos, Nikolaj Lindberg, Matt Hellige, David Vydra, Ricky Clarkson, Alex Cruise, Josh Cronemeyer, Tyler Jennings, Alan Supynuk, Tony Hillerson, Roger Vaughn, Arbi Sookazian, Bruce Leidl, Daniel Sobral, Eder Andres Avila, Marek Kubica, Henrik Huttunen, Bhaskar Maddala, Ged Byrne, Derek Mahar, Geoffrey Wiseman, Peter Rawsthorne, Geoffrey Wiseman, Joe Bowbeer, Alexander Battisti, Rob Dickens, Tim MacEachern, Jason Harris, Steven Grady, Bob Follek, Ariel Ortiz, Parth Malwankar, Reid Hochstedler, Jason Zaugg, Jon Hanson, Mario Gleichmann, David Gates, Zef Hemel, Michael Yee, Marius Kreis, Martin Süsskraut, Javier Vegas, Tobias Hauth, Francesco Bochicchio, Stephen Duncan Jr., Patrik Dudits, Jan Niehusmann, Bill Burdick, David Holbrook, Shalom Deitch, Jesper Nordenberg, Esa Laine, Gleb Frank, Simon Andersson, Patrik Dudits, Chris Lewis, Julian Howarth, Dirk Kuzemczak, Henri Gerrits, John Heintz, Stuart Roebuck, and Jungho Kim. Many other readers for whom we only have usernames also provided feedback. We wish to thank Zack, JoshG, ewilligers, abcoates, brad, teto, pjcj, mkleint, dandoyon, Arek, rue, acangiano, vkelman, bryanl, Jeff, mbaxter, pjb3, kxen, hipertracker, ctran, Ram R., cody, Nolan, Joshua, Ajay, Joe, and anonymous contributors. We apologize if we have overlooked anyone! Our editor, Mike Loukides, knows how to push and prod gentle. He’s been a great help throughout this crazy process. Many other people at O’Reilly were always there to answer our questions and help us move forward. Preface xxi

We thank Jonas Bonér for writing the Foreword for the book. Jonas is a longtime friend and collaborator from the aspect-oriented programming (AOP) community. For years, he has done pioneering work in the Java community. Now he is applying his energies to promoting Scala and growing that community. Bill Venners graciously provided the quote on the back cover. The first published book on Scala, Programming in Scala (Artima), that he cowrote with Martin Odersky and Lex Spoon, is indispensable for the Scala developer. Bill has also created the wonderful ScalaTest library. We have learned a lot from fellow developers around the world. Besides Jonas and Bill, Debasish Ghosh, James Iry, Daniel Spiewak, David Pollack, Paul Snively, Ola Bini, Daniel Sobral, Josh Suereth, Robey Pointer, Nathan Hamblen, Jorge Ortiz, and others have illuminated dark corners with their blog entries, forum discussions, and personal conversations. Dean thanks his colleagues at Object Mentor and several developers at client sites for many stimulating discussions on languages, software design, and the pragmatic issues facing developers in industry. The members of the Chicago Area Scala Enthusiasts (CASE) group have also been a source of valuable feedback and inspiration. Alex thanks his colleagues at Twitter for their encouragement and superb work in demonstrating Scala’s effectiveness as a language. He also thanks the Bay Area Scala Enthusiasts (BASE) for their motivation and community. Most of all, we thank Martin Odersky and his team for creating Scala. xxii Preface

CHAPTER 1 Zero to Sixty: Introducing Scala Why Scala? Today’s enterprise and Internet applications must balance a number of concerns. They must be implemented quickly and reliably. New features must be added in short, incremental cycles. Beyond simply providing business logic, applications must support secure access, persistence of data, transactional behavior, and other advanced features. Applications must be highly available and scalable, requiring designs that support concurrency and distribution. Applications are networked and provide interfaces for both people and other applications to use. To meet these challenges, many developers are looking for new languages and tools. Venerable standbys like Java, C#, and C are no longer optimal for developing the next generation of applications. If You Are a Java Programmer Java was officially introduced by Sun Microsystems in May of 1995, at the advent of widespread interest in the Internet. Java was immediately hailed as an ideal language for writing browser-based applets, where a secure, portable, and developer-friendly application language was needed. The reigning language of the day, C , was not suitable for this domain. Today, Java is more often used for server-side applications. It is one of the most popular languages in use for the development of web and enterprise applications. However, Java was a child of its time. Now it shows its age. In 1995, Java provided a syntax similar enough to C to entice C developers, while avoiding many of that language’s deficiencies and “sharp edges.” Java adopted the most useful ideas for the development problems of its era, such as object-oriented programming (OOP), while discarding more troublesome techniques, such as manual memory management. These design choices struck an excellent balance that minimized complexity and maximized developer productivity, while trading-off performance compared to natively compiled 1

code. While Java has evolved since its birth, many people believe it has grown too complex without adequately addressing some newer development challenges. Developers want languages that are more succinct and flexible to improve their productivity. This is one reason why so-called scripting languages like Ruby and Python have become more popular recently. The never-ending need to scale is driving architectures toward pervasive concurrency. However, Java’s concurrency model, which is based on synchronized access to shared, mutable state, results in complex and error-prone programs. While the Java language is showing its age, the Java Virtual Machine (JVM) on which it runs continues to shine. The optimizations performed by today’s JVM are extraordinary, allowing byte code to outperform natively compiled code in many cases. Today, many developers believe that using the JVM with new languages is the path forward. Sun is embracing this trend

What Is Functional Programming? 165 Functions in Mathematics 166 Variables that Aren't 166 Functional Programming in Scala 167 Function Literals and Closures 169 Purity Inside Versus Outside 169 Recursion 170 Tail Calls and Tail-Call Optimization 171 Trampoline for Tail Calls 172 Functional Data Structures 172 Lists in Functional Programming 173

Related Documents:

Getting Started in Scala scala Runs compiled scala code Or without arguments, as an interpreter! scalac - compiles fsc - compiles faster! (uses a background server to minimize startup time) Go to scala-lang.org for downloads/documentation Read Scala: A Scalable Language

Java Scala OO features Enough Scala functional features to use use the Scala API in Apache Spark Full-blown functional programming: Lambda calculus, category theory, closures, monads, functors, actors, promises, futures, combinators, functional design patterns, full type system, library construction techniques, reactive

Written in Scala Extensive use of Functional Programming 19 114383 6025 50557 128826 Lines 293K Total Scala Scala (Unit tests) TDML Tests C. . Functional Programming Idiom for Compilers Johnsson, Thomas. (1995). Attribute Grammars as a Functional Programming Paradigm. LNCS. 274. 10.1007/3-540-18317-5_10.

Functional Programming Scala Reduced defects rate Easier maintenance (tests, refactoring) Local reasoning Mathematical rigor We're hiring great people We're still learning It's fun! Functional Programming Scala. Payment-processing Destination Queue - Transaction is

PROGRAMMING USING SCALA MarkC.Lewis CRCPress Taylor&FrancisCroup BocaRaton London NewYork CRCPressis animprintofthe Taylor &FrancisGroup, anInforma business . 1.5.2 Functional Programming 11 1.5.3 Object-Oriented Programming 12 1.5.4 Logic Programming 13 1.5.5 Nature ofScala 13 1.6 EndofChapter Material 13 1.6.1 SummaryofConcepts 13

Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects. Scala can do Concurrent & Synchronize processing Scala allows you to express general programming patterns in an effective way. It reduces the number of lines and helps the programmer to code in a type-safe way.

Listing 1.1: Scala parallel collection impure lambda example 1.3 Scope There are many different programming languages featuring a combination of OOP and FP. Each of these languages has a unique combination of constructs. For this thesis, we have decided to focus on a single language, namely Scala. Scala has been designed as a combination of OOP

Illustration by: Steven Birch, Mary Peteranna Date of Fieldwork: 9-18 February 2015 Date of Report: 17th March 2015 Enquiries to: AOC Archaeology Group Shore Street Cromarty Ross-shire IV11 8XL Mob. 07972 259 255 E-mail inverness@aocarchaeology.com This document has been prepared in accordance with AOC standard operating procedures. Author: Mary Peteranna Date: 24/03/2015 Approved by: Martin .