Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Scala for Java Developers
Scala for Java Developers
Scala for Java Developers
Ebook506 pages3 hours

Scala for Java Developers

Rating: 5 out of 5 stars

5/5

()

Read preview

About this ebook

This stepbystep guide is full of easytofollow code taken from realworld examples explaining the migration and integration of Scala in a Java project.

If you are a Java developer or a Java architect, working in Java EEbased solutions and want to start using Scala in your daily programming, this book is ideal for you. This book will get you up and running quickly by adopting a pragmatic approach with realworld code samples. No prior knowledge of Scala is required.
LanguageEnglish
Release dateApr 25, 2014
ISBN9781783283644
Scala for Java Developers

Related to Scala for Java Developers

Related ebooks

Programming For You

View More

Related articles

Reviews for Scala for Java Developers

Rating: 5 out of 5 stars
5/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Scala for Java Developers - Thomas Alexandre

    Table of Contents

    Scala for Java Developers

    Credits

    Foreword

    About the Author

    Acknowledgments

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why Subscribe?

    Free Access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Programming Interactively within Your Project

    Advantages of using Scala for Java projects

    More concise and expressive

    Increased productivity

    Natural evolution from Java

    Better fit for asynchronous and concurrent code

    Learning Scala through the REPL

    Declaring val/var variables

    Defining classes

    Explaining case classes

    Operations on collections

    Transforming collections containing primitive types

    Collections of more complex objects

    Filter and partition

    Dealing with tuples

    Introducing Map

    Introducing the Option construct

    A glimpse at pattern matching

    The map method

    Looking at String Interpolation

    The groupBy method

    The foldLeft method

    Summary

    2. Code Integration

    Creating a REST API from an existing database

    The sample database

    Setting up a Maven project

    Creating JPA entities and REST web services

    Running and testing the project

    Adding a unit test in Java

    Adding a test in Scala

    Setting up Scala within a Java Maven project

    Scala and Java collaboration

    Converting between collection types

    JavaBean-style properties

    Scala and Java object orientation

    Scala traits as enhanced Java interfaces

    Declaring objects

    Introducing companion objects

    Handling exceptions

    Differences in style between Java and Scala code

    Adjusting the code layout

    Naming conventions

    Summary

    3. Understanding the Scala Ecosystem

    Inheriting Java Integrated Development Environments (IDEs)

    Building with Simple Build Tool (SBT)

    Getting started with SBT

    Creating a sample project

    Importing the project in Eclipse, IntelliJ IDEA, and NetBeans

    Creating a web application that runs on a servlet container

    Using sbt-assembly to build a single .jar archive

    Formatting code with Scalariform

    Experimenting with Scala Worksheets

    Working with HTTP

    Scala's for comprehension

    Taking advantage of Typesafe Activator

    Creating an application based on activator templates

    The REPL as a scripting engine

    Summary

    4. Testing Tools

    Writing tests with ScalaTest

    BDD-style testing

    Functional testing

    Mocking with ScalaMock

    Testing with ScalaCheck

    Summary

    5. Getting Started with the Play Framework

    Getting started with the classic Play distribution

    Getting started with the Typesafe Activator

    Architecture of a Play application

    Visualizing the framework stack

    Exploring the request-response lifecycle

    Handling a request in the controller

    Rendering the view

    Playing with authentication

    Practical tips when using Play

    Debugging with Play

    Dealing with version control

    Summary

    6. Database Access and the Future of ORM

    Integrating an existing ORM – Hibernate and JPA

    Making JPA available in Scala

    Dealing with persistence in the Play Framework

    A simple example using Anorm

    Replacing ORM

    Learning about Slick

    Scaffolding a Play application

    Importing test data

    Visualizing the database in the H2browser

    Exploring the code behind the app generation

    Limitations of the playcrud utility

    Summary

    7. Working with Integration and Web Services

    Binding XML data in Scala

    Running scalaxb from a SOAP web service

    Working with XML and JSON

    Manipulating XML

    Manipulating JSON

    Using Play JSON

    Handling Play requests with XML and JSON

    Mocking Play responses with JSON

    Calling web services from Play

    Summary

    8. Essential Properties of Modern Applications – Asynchrony and Concurrency

    The pillars of Concurrency

    The Async library – SIP-22-Async

    Combining web services

    Combining services without await

    Getting started with Akka

    Understanding the Actor model

    Switching behavior

    Supervising actors to handle failure

    Testing actor systems

    Exploring further with Akka

    Summary

    9. Building Reactive Web Applications

    Describing reactive applications

    Handling streams reactively

    Understanding Iteratees in Play

    Adapting Enumerator with Enumeratee

    Experimenting with WebSockets and Iteratees in Play

    Learning from activator templates

    Reactive stocks

    Reactive real-time search

    The Play-Akka-Angular-WebSocket template

    Playing with Actor Room

    Summary

    10. Scala Goodies

    Exploring MongoDB

    Entering Casbah

    Applying MapReduce transformations

    Scratching the surface of Big Data

    Introducing DSLs in Scala

    Observing internal DSLs

    Tackling external DSLs through parser combinators

    Introducing Scala.js

    Final tips

    Copying and pasting in the REPL

    Timing code execution in the REPL

    Summary

    Index

    Scala for Java Developers


    Scala for Java Developers

    Copyright © 2014 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: April 2014

    Production Reference: 1180414

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78328-363-7

    www.packtpub.com

    Cover Image by Grégoire Alexandre (<contact@gregoirealexandre.com>)

    Credits

    Author

    Thomas Alexandre

    Reviewers

    Carlos Estebes

    Tomer Gabel

    Eric Le Goff

    Steve Perkins

    Erik Wallin

    Commissioning Editor

    Kunal Parikh

    Acquisition Editors

    Rubal Kaur

    Neha Nagwekar

    Content Development Editors

    Neil Alexander

    Larissa Pinto

    Technical Editors

    Miloni Dutia

    Kunal Anil Gaikwad

    Kapil Hemnani

    Mukul Pawar

    Copy Editors

    Roshni Banerjee

    Deepa Nambiar

    Alfida Paiva

    Stuti Srivastava

    Laxmi Subramanian

    Sayanee Mukherjee

    Project Coordinator

    Akash Poojary

    Proofreaders

    Simran Bhogal

    Paul Hindle

    Maria Gould

    Stephen Copestake

    Indexer

    Monica Ajmera Mehta

    Graphics

    Ronak Dhruv

    Production Coordinator

    Nilesh Bambardekar

    Cover Work

    Nilesh Bambardekar

    Foreword

    I wish this book had been available when I first started my own Scala journey.

    As a Java developer, you must have heard a lot about Scala, even if you haven't yet written any Scala code. You must have noticed that Scala is becoming popular and heard vigorous debate about it. As I sat down to write this, I typed scala is into Google. The top completions included scala is awesome, scala is too complex, and scala is hard. Understandably, you may be confused by such polarization. You may also have heard arcane, possibly off-putting details about obscure Scala idioms and advanced functional programming.

    What you probably have not heard is a methodical, impartial attempt to answer questions such as might Scala make me more productive in my daily work?, will it be easy for me to pick up Scala?, and ultimately, Should I switch from Java to Scala?.

    Given the size of the Java community and the quality and ubiquity of the JVM, these are vital questions for many of us as developers and to our industry as a whole. Author Thomas Alexandre directly addresses them, presenting solid evidence in the form of working code. He shows that Scala is awesome, if awesome means providing elegant solutions to common, real world problems. He shows that "Scala is not hard" by listing the straightforward steps to each of those solutions. He shows how Scala code is usually less complex than the familiar Java code to solve the same problem. He equips you to answer the question of whether you want to switch from Java to Scala.

    The focus is on solving practical problem, and not on evangelizing language features for its own sake. Thomas explains core concept, such as functional programming, which may be relatively unfamiliar to Java developers, but his main emphasis is building on what the reader already knows. He does all this without a hint of the programming language chauvinism that often causes language debates to shed more heat than light.

    The topics covered are all relevant to everyday Java development. Naturally, there is material that is purely Scala related, such as the coverage of REPL (the Scala interactive interpreter that has no Java equivalent). However throughout the book, the emphasis is on how to use Scala to provide better solutions to familiar problem, such as accessing relational data from Java. The coverage of Scala/Java integration is particularly welcome, as the topic seldom gets the attention it deserves. (In fact, Scala is so important partly because it does not force developers to abandon Java and the JVM). The material is up to date: for example, in its coverage of new but important technologies such as Typesafe Activator.

    After reading this book, you will be ready to decide for yourself whether Scala is for you. Like Thomas and myself, you may well decide to program in Scala rather than Java when you have a choice. You will then be eager to learn more about functional programming and advanced Scala syntax, and you'll be ready for a more conceptual, reference-oriented book like Martin Odersky's Programming in Scala.

    Thomas Alexandre provides the perfect starter to whet the appetite of Java developers for the rich main course that Scala has to offer. Bon appetit!

    Rod Johnson

    Creator of Spring framework

    Co-founder of SpringSource

    About the Author

    Thomas Alexandre is a senior consultant at DevCode, specializing in Java and Scala software development. He is passionate about technology, enthusiastic about sharing knowledge, and is always looking for ways to code more effectively through the adoption of new open source software and standards. In addition to 15 years of Java development, he has focused these past few years on emerging languages and web frameworks such as Groovy and Scala. He also has a Ph.D. in Computer Science from the University of Lille, France, and has spent two years as a postdoc with Carnegie Mellon University in the fields of Security and E-commerce.

    Thomas is a certified trainer by Typesafe, the creators of Scala.

    Acknowledgments

    There are many people who have contributed to this book in one form or another and I would like to thank them for their help.

    First, I would like to thank Martin Odersky, the creator of Scala and co-founder of Typesafe for inspiring me through his fantastic lectures and two online courses to write this book. The online courses were written together with Erik Meijer and Roland Kuhn who are also to be thanked. I am also grateful to many Typesafe employees as well as Zengularity for creating and enhancing such amazing technologies. In particular, I would like to thank Viktor Klang and Jonas Bonér for their numerous tweets with links to great reading material and conference talks. Thanks to Heiko Seeberger and Trond Bjerkestrand for certifying me as a Typesafe Trainer for their Fast Track to Scala course.

    A big thank you to the very active Scala Community for all their contributions in terms of open source projects, talks at user groups, and workshops. The meetups at the Stockholm Scala User Group have been a good source of inspiration as well, thanks.

    The team at Packt Publishing has been very helpful and has done a great job at all levels in reviewing and producing this book. In particular, I would like to thank Akash Poojary, Neha Nagwekar, Neil Alexander, Miloni Dutia, Kunal Gaikwad, Mukul Pawar, Kunal Parikh, Rubal Kaur, Apeksha Chitnis, Larissa Pinto, Tomer Gabel, Steve Perkins, Eric Le Goff, and Sumeet Sawant for their extensive participation.

    Thank you to my employer and awesome colleagues at DevCode for all the encouragement they have given me. Special thanks go to my colleague Erik Wallin for putting much effort into technical review and producing very useful feedback under a tight schedule. Thank you to all my great friends and ex-colleagues as well for their support.

    Finally, I would like to thank my family. My parents have always supported me in everything I have been doing and I would like to thank them for that. I would like to thank my lovely wife Malin and awesome kids Valdemar (four years old) and Edvin (three years old) for their great patience and encouragement. Thank you to my parents-in-law for watching after the kids many a times during the writing of this book.

    Also, a big thank you to my talented brother Grégoire for realizing this terrific cover picture.

    I would like to express my sincere gratitude to Rod Johnson, creator of the Spring framework and co-founder of SpringSource, for his foreword.

    About the Reviewers

    Carlos Estebes is the founder of Ehxioz (http://ehxioz.com/), a Los Angeles-based software development startup that specializes in developing modern web applications and utilizing the latest web development technologies and methodologies. He has over 10 years of web development experience and holds a B.Sc. in Computer Science from California State University, Los Angeles.

    Carlos previously collaborated with Packt Publishing as a technical reviewer in the third edition of Learning jQuery and in jQuery Hotshot.

    Tomer Gabel is a programming junkie and computer history aficionado. He's been around the block a few times before settling at Wix (http://www.wix.com) as a system architect. In the last couple of years, he's developed a major crush on Scala, promoting it within the Israeli software industry as part of JJTV (Java & JVM Tel-Aviv user group) and Underscore (Israeli Scala user group), and finally organizing the Scalapeño conference in July 2013.

    Eric Le Goff is a senior Java developer and an open source evangelist. Located in Sophia-Antipolis, France, he has more than 15 years of experience in large-scale system designs and server-side development in both startups to established corporate Banking / Trading software, and more recently in Mobile Financial Services. A former board member of the OW2 consortium (an international open source community for infrastructure), he is also a Scala enthusiast certified with the Functional Programming Principles in Scala online course delivered by Martin Odersky (École Polytechnique Fédérale de Lausanne).

    I'd like to thank my wife Corine for all her support despite her own work constraints. I also want to thank all the contributors and the open source community at large who allow the delivery of reliable and innovative software.

    Steve Perkins is the author of Hibernate Search by Example, Packt Publishing (March 2013) and has over 15 years of experience working with Enterprise Java. He lives in Atlanta, GA, USA with his wife Amanda and their son Andrew. Steve currently works as an architect at BetterCloud, where he writes software for the Google cloud ecosystem. When he is not writing code, Steve plays the violin in a local community orchestra and enjoys working with music production software.

    I would like to thank my parents for all of their support over the years, and Martin Odersky, for opening up my mind to new ways of thinking about code.

    Erik Wallin holds an M.Sc. degree in Electrical Engineering and has worked as a software engineer since 2005, mostly on the Java platform. Clean and maintainable code is a great passion for Erik. He likes to use DDD and an expressive language such as Scala to accomplish this.

    Erik is employed as an IT consultant at DevCode. He has previously worked for IBM, Nanoradio, and ACE Interactive.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print and bookmark content

    On demand and accessible via web browser

    Free Access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    When I tell people around me that I now program in Scala rather than Java, I often get the question, So, in simple words, what is the main advantage of using Scala compared to Java? I tend to respond with this: With Scala, you reason and program closer to the domain, closer to plain English. Raising the level of abstraction is often the terminology employed to describe programs in a more readable and natural way for humans to understand rather than the zeros and ones understood by computers.

    As computer systems that are encountered in telecom, manufacturing or financial applications mature and grow, different forms of complexity tend to emerge, which are as follows:

    Complexity due to the addition of supported features, for example, the variety of contract alternatives in an insurance system or the introduction of complicated algorithms to solve new challenges in our evolving society

    Complexity to offset the limitations of technologies; for instance, making a system distributed to handle larger loads or improve reliability and response time

    Accidental complexity, which is introduced because of factors other than the problem at stake, such as integration between legacy systems and not really compatible technologies, short-term workarounds to reach the consumer market in a quicker way, or misunderstanding how a large system is designed as a whole when many resources with different backgrounds and styles are contributing in a short period of time to a large code base

    The third complexity is clearly unwanted and should be reduced to a minimum if not eliminated, whereas the other two should remain manageable. Scala tackles all of them, and the complexity of the business domain is something that will be manageable only if a system can be described in code as if it was described in well-written English.

    In the past few years, the ability of many languages to express behaviors in a more concise way than the traditional object-oriented way is largely due to the increasing popularity of functional programming (FP), a paradigm that has been around for a very long time but until recently thought of as a competitor to the so-called imperative programming languages such as C or Java. Michael Feathers nicely outlined the apparent duality between the two in the following statement:

    OO makes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts.

    The former focuses on breaking a large system into smaller, reusable parts. These parts are easy to reason about as they are modeled according to real-life objects. They use interfaces between them and are meant to encapsulate a mutating state. The latter emphasizes on the combination of functions that have ideally no side effects. It means that their result depends only on their input arguments, leading to minimizing or removing a mutating state in a program.

    The declarative nature of FP, supported by Scala, aims at writing code to express what is to be done rather than how to do it. Moreover, the FP approach tends to make algorithms more concise by composing (combining functions together), whereas the imperative approach tends to introduce side effects, that is, changes in the program state that will make it more difficult to see the algorithm, in its whole, in a concise way.

    This book will show Java developers that Scala is a significant yet natural evolution from Java by reasoning at a higher level of abstraction. Making the transition should ultimately lead to a more robust, maintainable, and fun software.

    The intent of this book is not so much about exploring the design or deep features of the language as well as its exhaustive syntax; there are already a number of excellent books about the Scala language, notably by the creator of the language himself, Martin Odersky, and people working with him at Typesafe.

    Our aim is to concentrate on helping current Java developers to get started and feel comfortable using the language, and to make their daily job more productive and fun.

    What this book covers

    Chapter 1, Programming Interactively within Your Project, provides a short introduction about the JVM (Java Virtual Machine) and some of the key features that have made Java successful. We will then start getting our hands dirty and experiment with the Scala REPL (short for, Read Eval Print Loop), a powerful tool to program interactively.

    Enjoying the preview?
    Page 1 of 1