scala in depth

306 692 0
scala in depth

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

MANNING Joshua D. Suereth FOREWORD BY Martin Odersky IN DEPTH www.it-ebooks.info Scala in Depth www.it-ebooks.info www.it-ebooks.info Scala in Depth JOSHUA D. SUERETH 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 ©2012 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: Katharine Osborne 20 Baldwin Road Technical proofreader: Justin Wick PO Box 261 Copyeditors: Linda Kern, Benjamin Berg Shelter Island, NY 11964 Proofreader: Elizabeth Martin Typesetter:Dottie Marsico Cover designer: Marija Tudor ISBN 9781935182702 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12 www.it-ebooks.info v contents foreword xi preface xiii acknowledgments xiv about this book xvi about the cover illustration xix 1 Scala—a blended language 1 1.1 Functional programming meets object orientation 2 Discovering existing functional concepts 4 ■ Examining functional concepts in Google Collections 6 1.2 Static typing and expressiveness 8 Changing sides 8 ■ Type inference 9 ■ Dropping verbose syntax 9 ■ Implicits are an old concept 10 ■ Using Scala’s implicit keyword 11 1.3 Transparently working with the JVM 12 Java in Scala 12 ■ Scala in Java 13 ■ The benefits of a JVM 14 1.4 Summary 15 www.it-ebooks.info CONTENTSvi 2 The core rules 16 2.1 Learn to use the Read Eval Print Loop (REPL) 16 Experiment-driven development 18 ■ Working around eager parsing 19 ■ Inexpressible language features 20 2.2 Think in expressions 21 Don’t use return 22 ■ Mutability 24 2.3 Prefer immutability 26 Object equality 27 ■ Concurrency 31 2.4 Use None instead of null 34 Advanced Option techniques 35 2.5 Polymorphic equality 38 Example: A timeline library 38 ■ Polymorphic equals implementation 40 2.6 Summary 42 3 Modicum of style—coding conventions 43 3.1 Avoid coding conventions from other languages 44 The block debacle 45 3.2 Dangling operators and parenthetical expressions 48 3.3 Use meaningful variable names 49 Avoid $ in names 50 ■ Working with named and default parameters 53 3.4 Always mark overridden methods 55 3.5 Annotate for expected optimizations 60 Using the tableswitch optimization 61 ■ Using the tail recursion optimization 64 3.6 Summary 66 4 Utilizing object orientation 68 4.1 Limit code inside an object or trait’s body to initialization logic 69 Delayed construction 69 ■ And then there’s multiple inheritance 70 4.2 Provide empty implementations for abstract methods on traits 72 www.it-ebooks.info CONTENTS vii 4.3 Composition can include inheritance 76 Member composition by inheritance 78 ■ Classic constructors with a twist 80 4.4 Promote abstract interface into its own trait 82 Interfaces you can talk to 84 ■ Learning from the past 85 4.5 Provide return types in your public APIs 86 4.6 Summary 88 5 Using implicits to write expressive code 89 5.1 Introduction to implicits 90 Identifiers: A digression 91 ■ Scope and bindings 92 Implicit resolution 96 5.2 Enhancing existing classes with implicit views 101 5.3 Utilize implicit parameters with defaults 106 5.4 Limiting the scope of implicits 112 Creating implicits for import 113 ■ Implicits without the import tax 115 5.5 Summary 119 6 The type system 120 6.1 Types 121 Types and paths 122 ■ The type keyword 124 ■ Structural types 125 6.2 Type constraints 131 6.3 Type parameters and higher-kinded types 134 Type parameter constraints 134 ■ Higher-kinded types 135 6.4 Variance 137 Advanced variance annotations 141 6.5 Existential types 144 The formal syntax of existential types 146 6.6 Summary 149 7 Using implicits and types together 150 7.1 Context bounds and view bounds 151 When to use implicit type constraints 152 www.it-ebooks.info CONTENTSviii 7.2 Capturing types with implicits 153 Manifests 153 ■ Using Manifests 154 ■ Capturing type constraints 156 ■ Specialized methods 158 7.3 Use type classes 159 FileLike as a type class 163 ■ The benefits of type classes 166 7.4 Conditional execution using the type system 167 Heterogeneous typed list 169 ■ IndexedView 172 7.5 Summary 178 8 Using the right collection 179 8.1 Use the right collection 180 The collection hierarchy 180 ■ Traversable 182 Iterable 185 ■ Seq 187 ■ LinearSeq 187 IndexedSeq 189 ■ Set 190 ■ Map 191 8.2 Immutable collections 192 Vector 192 ■ List 194 ■ Stream 195 8.3 Mutable collections 198 ArrayBuffer 198 ■ Mixin mutation event publishing 199 ■ Mixin synchronization 200 8.4 Changing evaluation with views and parallel collections 200 Views 201 ■ Parallel collections 203 8.5 Writing methods to use with all collection types 205 Optimizing algorithms for each collections type 209 8.6 Summary 211 9 Actors 212 9.1 Know when to use actors 213 Using actors to search 213 9.2 Use typed, transparent references 216 Scatter-Gather with OutputChannel 217 9.3 Limit failures to zones 221 Scatter-Gather failure zones 221 ■ General failure handling practices 224 9.4 Limit overload using scheduler zones 225 Scheduling zones 227 www.it-ebooks.info CONTENTS ix 9.5 Dynamic actor topology 228 9.6 Summary 233 10 Integrating Scala with Java 234 10.1 The language mismatch between Scala and Java 235 Differences in primitive boxing 236 ■ Differences in visibility 240 ■ Inexpressible language features 241 10.2 Be wary of implicit conversions 244 Object identity and equality 245 ■ Chaining implicits 246 10.3 Be wary of Java serialization 248 Serializing anonymous classes 250 10.4 Annotate your annotations 252 Annotation targets 254 ■ Scala and static fields 255 10.5 Summary 256 11 Patterns in functional programming 257 11.1 Category theory for computer science 258 11.2 Functors and monads, and how they relate to categories 262 Monads 264 11.3 Currying and applicative style 266 Currying 266 ■ Applicative style 268 11.4 Monads as workflows 272 11.5 Summary 276 index 277 www.it-ebooks.info [...]... clean In all instances, the type of the name x is Int Table 1.2 Variable definition in C++ versus Scala Variable type C++ Java Scala Mutable integer variable int x int x var x: Int Immutable integer value const int x final int x val x: Int Constant pointer to a volatile integer volatile int * const x N/A N/A Lazily evaluated integer value N/A N/A lazy val x: Int www.it-ebooks.info 9 Static typing and... working examples is available from www.manning.com/ ScalainDepth and at https://github.com/jsuereth /scala- in- depth- source To run the examples, readers should have Scala installed and, optionally, SBT (http://scalasbt.org) Code examples appear throughout this book Longer listings appear under clear listing headers; shorter listings appear between lines of text Author online Purchase of Scala in Depth includes... departments in the discovery of disease outbreaks He introduced Scala into his company code base in 2007, and soon after he was infected by Scala fever, contributing to the Scala IDE, maven -scala- plugin and Scala itself Today, Josh is the author of several open source Scala projects, including the Scala automated resource management library and the PGP sbt plugin, as well as contributing to key components in. .. book is in a fixed-width font like this, which sets it off from the surrounding text In many listings, the code is annotated to point out the key www.it-ebooks.info xviii ABOUT THIS BOOK concepts I have tried to format the code so that it fits within the available page space in the book by adding line breaks and using indentation carefully Sometimes, however, very long lines include line-continuation... traits don’t map into Java, the passing of first-class functions from Java into Scala is also inhibited but not impossible object FunctionUtil { def testFunction(f : Int => Int) : Int = f(5) } abstract class AbstractFunctionIntIntForJava extends (Int => Int) { } www.it-ebooks.info Special abstract class to use from Java 14 CHAPTER 1 Scala a blended language We’ve created an abstract class in Scala that... does this through various techniques Including the following:  Method inlining  On Stack Replacement (OSR)  Escape Analysis  Dynamic deoptimization www.it-ebooks.info Summary 15 Method inlining is HotSpot’s ability to determine when it can inline a small method directly at a call-spot This was a favorite technique of mine in C++, and HotSpot will dynamically determine when this is optimal On Stack... Java libraries and integrate Scala into their Java applications while also gaining the additional power of Scala This integration makes Scala a practical choice for any JVMbased project Let’s take a deeper look at the blending of paradigms in Scala 1.1 Functional programming meets object orientation Functional programming and object-oriented programming are two different ways of looking at a problem... experience with Scala is helpful but not required It covers Scala 2.7.x through Scala 2.9.x Roadmap Scala in Depth begins with a philosophical discussion of the “xen” of Scala that Scala is a blending of concepts that achieve a greater whole when combined In particular, three dichotomies are discussed: static typing versus expressiveness, functional programming versus object-oriented programming, and powerful... care was taken in the design so that seamless Java interaction can be achieved For the most part, libraries written in Java can be imported into Scala as is 1.3.1 Java in Scala Using Java libraries from Scala is seamless because Java idioms map directly into Scala idioms Java classes become Scala classes; Java interfaces become abstract Scala traits Java static members get added to a pseudo -Scala object... unused in Scala, they provide a convenient syntax when called from Java object ScalaUtils { def log(msg : String) : Unit = Console.println(msg) Simple Scala method val MAX_LOG_SIZE = 1056 Simple Scala field ScalaUtils.log("Hello!"); Acts like static call } ScalaUtils$.MODULE$.log("Hello!"); Use the singleton instance System.out.println(ScalaUtils$.MODULE$.MAX_LOG_SIZE()); System.out.println(ScalaUtils.MAX_LOG_SIZE()); . MANNING Joshua D. Suereth FOREWORD BY Martin Odersky IN DEPTH www.it-ebooks.info Scala in Depth www.it-ebooks.info www.it-ebooks.info Scala in Depth JOSHUA D. SUERETH MANNING SHELTER. authoring Lift in Action for Manning around the same time I was writing Scala in Depth. Discus- sions with Tim were both encouraging and motivating. Unfortunately for me, he fin- ished first. Justin. for persevering through my rough initial cuts and making it to this final version. www.it-ebooks.info xvi about this book Scala in Depth is a practical guide to using Scala with deep dives into necessary

Ngày đăng: 28/04/2014, 16:59

Mục lục

  • Scala In Depth

  • contents

  • foreword

  • preface

  • acknowledgments

  • about this book

    • Who should read this book?

    • Roadmap

    • Code downloads and conventions

    • Author online

    • About the author

    • about the cover illustration

    • 1 Scala— a blended language

      • 1.1 Functional programming meets object orientation

        • 1.1.1 Discovering existing functional concepts

        • 1.1.2 Examining functional concepts in Google Collections

        • 1.2 Static typing and expressiveness

          • 1.2.1 Changing sides

          • 1.2.2 Type inference

          • 1.2.3 Dropping verbose syntax

          • 1.2.4 Implicits are an old concept

          • 1.2.5 Using Scala’s implicit keyword

          • 1.3 Transparently working with the JVM

            • 1.3.1 Java in Scala

            • 1.3.2 Scala in Java

Tài liệu cùng người dùng

Tài liệu liên quan