MANNING IN ACTION Nilanjan Raychaudhuri FOREWORD BY Chad Fowler Covers Scala 2.10 www.it-ebooks.info Scala in Action www.it-ebooks.info www.it-ebooks.info Scala in Action NILANJAN RAYCHAUDHURI MANNING SHELTER ISLAND www.it-ebooks.info For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: orders@manning.com ©2013 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Cynthia Kane 20 Baldwin Road Technical Proofreaders: Ivan Kirkpatrick, Clint Combs PO Box 261 Copyeditor: Corbin Collins Shelter Island, NY 11964 Proofreader: Elizabeth Martin Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781935182757 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 18 17 16 15 14 13 www.it-ebooks.info v brief contents PART 1 SCALA: THE BASICS 1 1 ■ Why Scala? 3 2 ■ Getting started 20 3 ■ OOP in Scala 55 4 ■ Having fun with functional data structures 93 5 ■ Functional programming 132 PART 2 WORKING WITH SCALA . 167 6 ■ Building web applications in functional style 169 7 ■ Connecting to a database 193 8 ■ Building scalable and extensible components 224 9 ■ Concurrency programming in Scala 255 10 ■ Building confidence with testing 283 PART 3 ADVANCED STEPS. 321 11 ■ Interoperability between Scala and Java 323 12 ■ Scalable and distributed applications using Akka 344 www.it-ebooks.info www.it-ebooks.info vii contents foreword xiii preface xv acknowledgments xvi about this book xvii about the cover illustration xxi PART 1 SCALA: THE BASICS 1 1 Why Scala? 3 1.1 What’s Scala? 4 Scala as an object-oriented language 4 ■ Scala as a functional language 6 ■ Scala as a multi-paradigm language 8 Scala as a scalable and extensible language 9 ■ Scala runs on the JVM 10 1.2 The current crisis 11 End of Moore’s law 11 ■ Programming for multicores 11 1.3 Transitioning from Java to Scala 13 Scala improves productivity 13 ■ Scala does more with less code 13 1.4 Coming from a dynamic language 15 Case for static typing, the right way 16 www.it-ebooks.info CONTENTSviii 1.5 For the programming language enthusiast 18 1.6 Summary 18 2 Getting started 20 2.1 REPL with Scala interpreter 21 2.2 Scala basics 22 Basic types 23 ■ Defining variables 28 ■ Defining functions 30 2.3 Working with Array and List 36 2.4 Controlling flow with loops and ifs 38 2.5 For-comprehensions 39 2.6 Pattern matching 42 2.7 Exception handling 45 2.8 Command-line REST client: building a working example 46 Introducing HttpClient library 48 ■ Building the client, step by step 49 2.9 Summary 54 3 OOP in Scala 55 3.1 Building a Scala MongoDB driver: user stories 56 3.2 Classes and constructors 57 3.3 Packaging 61 3.4 Scala imports 63 3.5 Objects and companion objects 65 3.6 Mixin with Scala traits 69 Class linearization 75 ■ Stackable traits 77 3.7 Case class 78 3.8 Named and default arguments and copy constructors 83 3.9 Modifiers 86 3.10 Value classes: objects on a diet 87 3.11 Implicit conversion with implicit classes 88 3.12 Scala class hierarchy 91 3.13 Summary 92 www.it-ebooks.info CONTENTS ix 4 Having fun with functional data structures 93 4.1 Introducing type parameterization 94 4.2 Type variance with covariance and contravariance 95 4.3 Lower and upper type bounds 99 4.4 Higher-order functions, including map, flatMap, and friends 101 4.5 Using foldLeft and foldRight 106 4.6 Building your own function objects 108 4.7 Scala collection hierarchy 110 4.8 Mutable and immutable collections 113 4.9 Working with List and ListBuffer 114 Working with Set and SortedSet 115 ■ Working with Map and Tuple 117 ■ Under the hood of for-comprehension 118 Use Option not Null 121 4.10 Working with lazy collections: views and streams 122 Convert a strict collection to a nonstrict collection with views 123 Working with Streams 125 4.11 Divide and conquer with parallel collections 127 Parallel collection hierarchy 129 ■ Switching between sequential and parallel collections 130 4.12 Summary 131 5 Functional programming 132 5.1 What is functional programming? 133 The benefits of referential transparency 134 ■ A pure functional program 135 5.2 Moving from OOP to functional programming 135 Pure vs. impure programming 136 ■ Object-oriented patterns in functional programming 137 ■ Modeling purely functional programs 138 5.3 Functions in all shapes and forms 140 Methods vs. functions 141 ■ Higher-order functions 141 Function currying 144 ■ Function composition and partial functions 145 ■ Recursion 148 5.4 Thinking recursively 149 Tail recursion 150 www.it-ebooks.info [...]... between Scala and Java 11.1 Using Java classes in Scala 323 324 Working with Java static members 325 Working with Java checked exceptions 326 Working with Java generics using existential types 327 ■ ■ 11.2 Using Scala classes in Java Using Scala annotations 11.3 329 330 Building web applications in Scala using Java frameworks 332 Building the model, view, and controller 334 Configuring and running the... expertise in programming is far more strongly related to the number of different programming styles understood by an individual than it is the number of years of experience in programming.” How can Scala combine these two different and almost opposite paradigms into one programming language? In the case of OOP, building blocks are objects, and in functional programming building blocks are functions In Scala, ... succinctness of Scala, you have to dive into the code The next two listings provide a simple example of finding an uppercase character in a given string, comparing Scala and Java code Listing 1.2 Finding an uppercase character in a string using Java boolean hasUpperCase = false; for(int i = 0; i < name.length(); i++) { if(Character.isUpperCase(name.charAt(i))) { hasUpperCase = true; break; } } In this code... 2 In Scala this expression is interpreted as 1.+(2) by the Scala compiler That means you’re invoking a + operation on an integer object (in this case, 1) by passing 2 as a parameter Scala treats operator names like ordinary identifiers An identifier in Scala is either a sequence of letters and digits starting with a letter or a sequence of operator characters In addition to +, it’s possible to define... SBT Setting up the weKanban project with SBT 181 ■ 6.3 173 Introducing the Scalaz HTTP module 183 How the Scalaz HTTP library works 183 Configuring Scalaz with SBT 187 Building your first web page using Scalaz 189 ■ ■ 6.4 7 Summary 192 Connecting to a database 7.1 193 Adding a new story to a weKanban board 194 Connecting to a database using Squeryl 194 Saving a new story to the database 200 Building the... Postfunctional Language,” www .scala- lang.org/node/4960 Scala: A Scalable Language” by Martin Odersky, Lex Spoon, and Bill Venners, Scalazine, May 6, 2008, www.artima.com/scalazine/articles/scalable-language.html www.it-ebooks.info 10 CHAPTER 1 Why Scala? succinct syntax, and support for both object-oriented and functional programming make the language scalable Scala also provides a unique combination of language... functional programming matter? 153 Building higher abstractions with monads 156 Managing state using monads monads 163 5.8 PART 2 6 Summary 157 ■ Building blocks for 165 WORKING WITH SCALA 167 Building web applications in functional style 6.1 6.2 169 Building weKanban: a simple web-based Kanban board 170 Building Scala applications using Simple Build Tool 171 Setting up SBT 172 Understanding the basics... core with actors 364 Increase scalability with remote actors, dispatchers, and routers 368 Handling shared resources with Agent 374 ■ ■ ■ 12.4 Adding asynchronous HTTP support with Play2-mini 375 Setting up Play2-mini 12.5 Summary index 376 ■ Running with Play2-mini 379 381 www.it-ebooks.info 377 foreword You’re standing in front of a huge, steep wall of rock Your neck is straining as you bend your... combining functional programming with object-oriented programming in Scala is treating functions as objects Scala, being a functional language, treats functions as values, and you saw one example of assigning a function to a variable Because all values in Scala are objects, it follows that functions are objects too Look at the previous example again: List(1, 2, 3).map((x: Int) => x + 1) You’re passing... applications, starting with building a large messaging layer for social networking sites such as Twitter1 to creating an application 1 “Twitter on Scala: A Conversation with Steve Jenson, Alex Payne, and Robey Pointer,” Scalazine, April 3, 2009, www.artima.com/scalazine/articles/twitter_on _scala. html 3 www.it-ebooks.info 4 CHAPTER 1 Why Scala? build tool like SBT2 (Simple Build Tool) Because of this scala- bility, . MANNING IN ACTION Nilanjan Raychaudhuri FOREWORD BY Chad Fowler Covers Scala 2.10 www.it-ebooks.info Scala in Action www.it-ebooks.info www.it-ebooks.info Scala in Action NILANJAN. Scala classes in Java 329 Using Scala annotations 330 11.3 Building web applications in Scala using Java frameworks 332 Building the model, view, and controller 334 Configuring and running the application. would discourage you from doing that when reading Scala in Action. Scala is a new programming language that brings myriad new ideas to the Java virtual machine platform. Scala is unique. It is a