Toby Weston

Scala for Java Developers

A Practical Primer

Toby Weston

London, UK

Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book's product page, located at www.apress.com/9781484231074 . For more detailed information, please visit http://www.apress.com/source-code .

ISBN 978-1-4842-3107-4

e-ISBN 978-1-4842-3108-1

https://doi.org/10.1007/978-1-4842-3108-1

Library of Congress Control Number: 2017963118

© Toby Weston 2018

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

In memory of Félix Javier García López

Preface

Audience

This book is for Java developers looking to transition to programming in Scala.

The Structure of the Book

The book is split into four parts: a tour of Scala, a comparison between Java and Scala, a closer look at Scala-specific features and functional programming idioms, and finally a discussion about adopting Scala into existing Java teams.

In Part I, we’re going to take a high-level tour of Scala. You’ll get a feel for the language’s constructs and how Scala is similar in a lot of ways to Java, yet very different in others. We’ll take a look at installing Scala and using the interactive interpreter and we’ll go through some basic syntax examples.

Part II talks about key differences between Java and Scala. We’ll look at what’s missing in Scala compared to Java, vice versa, and how concepts translate from one language to another.

Then in Part III, we’ll talk about some of the language features that Scala offers that aren’t found in Java. This part also talks a little about functional programming idioms.

Finally, we’ll talk about adopting Scala into legacy Java projects and teams. It’s not always an easy transition, so we’ll look at why you would want to, and some of the challenges you might face.

Compiling Code Fragments

Later in the book, I introduce the Scala REPL: an interactive tool for working with Scala and the Scala version of Java’s JShell. You’ll see REPL sessions prefixed with scala> .

When you do so, you can expect to be able to type in the code following scala> in the REPL verbatim, hit enter, and see the results. An example follows.

// an example REPL session                  
  scala> val x = 6 * 9
  x: Int = 54

If you don’t see the scala> prefix, assume the fragment may depend on previous code examples. I’ve tried to introduce these logically, balancing the need to show complete listings with trying to avoid pages and pages of dry code listings.

If things don’t make sense, always refer to the full source code. In short, you may find it useful to consult the full source while you read.

Infrequently, you may notice an ellipsis ( ... ) or triple question marks ( ??? ) in code fragments. When you see this, it indicates that the fragment is incomplete and will usually be followed by additional code to fill in the blanks. It probably won’t compile. It’s used when I’ve felt that additional code would be uninteresting, distracting, or when I’m building up examples.

Source Code

The source code for this book is available at GitHub: https://github.com/tobyweston/learn-scala-java-devs . You can clone the repository or download an archive directly from the site.

The source code is licensed under Apache 2.0 open source license.

Source Code Appendix

The book often includes partial code fragments in an attempt to avoid reams of distracting “scaffolding” code. Code may refer to previous fragments and this may not be immediately obvious. Try to read the code as if each example builds on what’s gone before.

If this style isn’t for you, I’ve also included a code listing appendix. This offers complete listings for the more complex code, in case you want to see all the code in one place. It’s not there to pad out the book. Honest.

Acknowledgments

Thanks go out to James Maggs, Alex Luker, Rhys Keepence and Xuemin Guan for their feedback on early drafts and Lee Benfield for building the excellent CFR decompiler and sharing it with the community.

Additionally, thank you to Amy Brown for providing an early copyedit of this book.

Table of Contents

  1. Part I: Scala Tour 1
    1. Chapter 1:​ The Scala Language
      1. As a Functional Programming Language
      2. The Past
      3. The Future
    2. Chapter 2:​ Installing Scala
      1. Getting Started
      2. The Scala Interpreter
      3. Scala Scripts
      4. scalac
    3. Chapter 3:​ Some Basic Syntax
      1. Defining Values and Variables
      2. Defining Functions
      3. Operator Overloading and Infix Notation
      4. Collections
      5. Tuples
      6. Java Interoperability​
      7. Primitive Types
    4. Chapter 4:​ Scala’s Class Hierarchy
      1. AnyVal
      2. Unit
      3. AnyRef
      4. Bottom Types
    5. Chapter 5:​ ScalaDoc
    6. Chapter 6:​ Language Features
      1. Working with Source Code
      2. Working with Methods
      3. Functional Programming
    7. Chapter 7:​ Summary
  2. Part II: Key Syntactical Differences 39
    1. Chapter 8:​ Classes and Fields
      1. Creating Classes
      2. Derived Setters and Getters
      3. Redefining Setters and Getters
      4. Summary
    2. Chapter 9:​ Classes and Objects
      1. Classes Without Constructor Arguments
      2. Additional Constructors
        1. Using Default Values
      3. Singleton Objects
      4. Companion Objects
        1. Other Uses for Companion Objects
    3. Chapter 10:​ Classes and Functions
      1. Anonymous Functions
      2. Anonymous Classes
      3. First-class Functions
        1. Passing in Functions
        2. Returning Functions
        3. Storing Functions
      4. Function Types
      5. Functions vs.​ Methods
      6. Lambdas vs.​ Closures
    4. Chapter 11:​ Inheritance
      1. Subtype Inheritance
      2. Anonymous Classes
      3. Interfaces/​Traits
        1. Methods on Traits
        2. Converting Anonymous Classes to Lambdas
        3. Concrete Fields on Traits
        4. Abstract Fields on Traits
      4. Abstract Classes
      5. Polymorphism
        1. Traits vs.​ Abstract Classes
      6. Deciding Between the Options
    5. Chapter 12:​ Control Structures
      1. Conditionals
        1. Ifs and Ternaries
        2. Switch Statements
      2. Looping Structures:​ do, while and for
      3. Breaking Control Flow (break and continue)
      4. Exceptions
    6. Chapter 13:​ Generics
      1. Parametric Polymorphism
        1. Class Generics
        2. Method Generics
        3. Stack Example
      2. Bounded Classes
        1. Upper Bounds (<U extends T>)
        2. Lower Bounds (<U super T>)
        3. Wildcard Bounds (<?​ extends T, <?​ super T>)
        4. Multiple Bounds
      3. Variance
        1. Invariance
        2. Covariance
        3. Contravariance
        4. Variance Summary
  3. Part III: Beyond Java to Scala 141
    1. Chapter 14:​ Faking Function Calls
      1. The apply Method
      2. The update Method
        1. Multiple update Methods
        2. Multiple Arguments to update
      3. Summary
    2. Chapter 15:​ Faking Language Constructs
      1. Curly Braces (and Function Literals)
        1. Higher-Order Functions
        2. Higher-Order Functions with Curly Braces
        3. Call-by-Name
      2. Currying
        1. Scala Support for Curried Functions
      3. Summary
    3. Chapter 16:​ Pattern Matching
      1. Switching
      2. Patterns
      3. Literal Matches
      4. Constructor Matches
      5. Type Query
      6. Deconstruction Matches and unapply
        1. Why Write Your Own Extractors?​
      7. Guard Conditions
    4. Chapter 17:​ Map and FlatMap
      1. Mapping Functions
        1. It’s Like foreach
      2. FlatMap
      3. Not Just for Collections
    5. Chapter 18:​ Monads
      1. Basic Definition
      2. Option
        1. The map Function
        2. Option.​get
        3. Option.​getOrElse
        4. Monadically Processing Option
        5. The Option.​flatMap Function
      3. More Formal Definition
      4. Summary
    6. Chapter 19:​ For Comprehensions
      1. Where We Left Off
      2. Using Null Checks
      3. Using flatMap with Option
      4. How For Comprehensions Work
      5. Finally, Using a For Comprehension for Shipping Labels
      6. Summary
  4. Part IV: Adopting Scala in Java Teams 197
    1. Chapter 20:​ Adopting Scala
      1. Avoid Not Enough
      2. Don’t Do Too Much
      3. Purely Functional FTW?​
    2. Chapter 21:​ What to Expect
      1. The Learning Curve
      2. The Learning Continuum
        1. Goals
    3. Chapter 22:​ Tips
      1. Be Clear
      2. Get Guidance
      3. Have a Plan
    4. Chapter 23:​ Convert Your Codebase
    5. Chapter 24:​ Manage Your Codebase
      1. Conventions
      2. What to Avoid
      3. Other Challenges
  5. Appendix A: Code Listings
  6. Inheritance
  7. Subtype Inheritance in Java
  8. Anonymous Classes in Java
  9. Subtype Inheritance in Scala
  10. Anonymous Classes in Scala
  11. Generics
  12. Lower Bounds in Java
  13. Multiple Bounds in Java
  14. Lower Bounds in Scala
  15. Multiple Bounds in Scala
  16. Pattern Matching
  17. Constructor Matches
  18. Deconstruction Matches and Unapply
  19. Map
  20. Mapping Functions
  21. FlatMap
  22. Appendix B: Syntax Cheat Sheet
  23. Index

About the Author and About the Technical Reviewer

About the Author

Toby Weston is an independent software developer based in London. He specializes in Java and Scala development, working in agile environments. He’s a keen blogger and writer, having written for JAXenter and authored the books Essential Acceptance Testing (Leanpub) and Learning Java Lambdas (Pact).

About the Technical Reviewer

Jeff Friesen is a freelance teacher and software developer with an emphasis on Java. In addition to authoring Java I/O, NIO and NIO.2 (Apress) and Java Threads and the Concurrency Utilities (Apress), Jeff has written numerous articles on Java and other technologies (such as Android) for JavaWorld ( JavaWorld.com ), informIT ( informIT.com ), Java.net, SitePoint ( SitePoint.com ), and other websites. Jeff can be contacted via his website at JavaJeff.ca . or via his LinkedIn profile ( www.linkedin.com/in/javajeff ).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.233.205