Learn Scala Programming A comprehensive guide covering functional and reactive programming with Scala 2.13, Akka, and Lagom Slava Schmidt BIRMINGHAM - MUMBAI Learn Scala Programming Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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. Commissioning Editor: Merint Mathew Acquisition Editor: Shriram Shekhar Content Development Editor: Manjusha Mantri Technical Editor: Mehul Singh Copy Editor: Safis Editing Project Coordinator: Prajakta Naik Proofreader: Safis Editing Indexer: Priyanka Dhadke Graphics: Jisha Chirayil Production Coordinator: Nilesh Mohite First published: October 2018 Production reference: 1311018 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78883-630-2 www.packt.com To my family – Tanja, Christina, and Marina – who made this book possible. mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals Improve your learning with skill plans designed especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content Packt.com 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.packt.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.packt.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. Contributors About the author Slava Schmidt is a software developer living in Germany. During his career, he has used a wide spectrum of programming languages, ranging from Assembler to Haskell, and progressed from an intern programmer, via head of engineering, to a Scala contractor. In his current role, he helps to develop and bring into production a number of Scala projects of various sizes and complexities for customers from different industries. He is a contributor to open source projects related to Scala and Akka. As a passionate conference speaker, he regularly gives talks about technologies to share his experiences with other developers. I'd like to thank Tatjana Schmidt for making the images in this book look great, Mike Litvin for his timely support, Marco Borst for (in)validating lots of ideas (without necessarily knowing this) and the production team at Packt, especially Manjusha Mantri, for all of their advice and assistance. About the reviewers Rambabu Posa has 14 years of rich experience in Scala, Java, and BigData ecosystems. He has been working as Java developer since 2004 and Scala/BigData Developer since Mid of 2015. He loves functional programming in TDD (test-driven development) as a way of developing reactive microservices. He loves teaching, and has provided online training and written tutorials on Java, Scala, Cloud and BigData ecosystems. He loves developing Reactive systems using Lightbend's Reactive Platform technology stack, including Lagom Framework, ConductR, Scala, Akka Toolkit, Akka Streams, and Play Framework with AWS. He is a master of Apache Kafka (Kafka, KStreams, Connect, Schema Registry, Mirror Maker). Mikhail Litvin is a passionate software engineer with more than 10 years experience in systems analysis, software design, and software architecture. During the day, Mikhail spends his time building highly scalable and resilient solutions for one of the leading Europe, e-commerce companies. Mikhail works with a variety of technologies such as, Scala, Akka, SQL/ NoSQL, AWS, Python, and others. He's interested in artificial intelligence and machine learning. In a spare time, Mikhail enjoys riding his bicycle, fishing, and traveling. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Chapter 1: An Introduction to Scala 2.13 8 Technical requirements 8 Introduction to Scala 2.13 8 New features of Scala 2.13 9 Optional parsing for string literals 9 Products can report the names of their element 10 Added methods for chaining operations 11 Automatic Resource Management 13 The Scala 2.13 Collection Library 14 IterableOnceOps 16 IterableOps 17 WithFilter 18 IterableFactory 19 View 19 Set 21 Map 23 SortedMap 24 HashMap 24 MultiMap 25 SeqMap 25 Seq 25 IndexedSeq 27 LinearSeq 28 Buffers 29 Scala Collection Contrib library 30 Summary 31 Questions 32 Further reading 32 Chapter 2: Understanding Types in Scala 33 Technical requirements 33 Understanding types 34 Ways to create a type 34 Literal types 35 Compound (intersection) types 38 Type constraints 39 Scala's types hierarchy and special types 40 Type inference 42 Path-dependent types 43 Table of Contents Types – all the way down 45 Type parameters 45 Type members 46 Generalized type constraints 49 Infix types 49 Variance 50 Existential types 53 Higher kinded types 54 Type lambdas 55 Using types to define domain constraints 56 Phantom types 56 Self-recursive types 59 Summary 61 Questions 61 Further reading 62 Chapter 3: Deep Dive into Functions 63 Technical requirements 63 Ways to define a function 64 Function as a method 64 Local functions 66 Closures 67 Partial application and functions 68 Function literals 70 Currying 72 Polymorphism and higher order functions 72 Polymorphic functions 73 Higher-order functions 74 Recursion and trampolining 75 Recursion 76 Tail recursion 77 Trampolining 79 Object-oriented aspects of functions 80 Functions are traits 81 Partial functions 82 Function object 83 Extending functions 84 Summary 85 Questions 85 Further reading 86 Chapter 4: Getting to Know Implicits and Type Classes 87 Technical requirements 87 Types of implicits 88 Implicit conversions 88 [ ii ] Table of Contents Implicit parameters 91 Implicit classes 94 View and context bounds 95 View bounds 95 Context bounds 96 Type classes 97 Type classes 98 Type class recursive resolution 100 Type class variance 103 Implicit scope resolution 105 Lexical scope 106 Implicit scope 107 Static overloading rules 108 Summary 109 Questions 110 Further reading 110 Chapter 5: Property-Based Testing in Scala 111 Technical requirements 111 Introduction to property-based testing 112 From unit tests to properties 112 ScalaCheck 113 Properties 114 Types of properties 114 Commutativity 114 Associativity 115 Identity 116 Invariants 116 Idempotence 117 Induction 117 Symmetry 118 Test Oracle 118 Defining a property 119 Checking property 119 Combining properties 120 Generators 121 Existing generators 122 Combining generators 123 Shrinkers 126 Summary 128 Questions 129 Chapter 6: Exploring Built-In Effects 130 Technical requirements 130 Introduction to effects 131 Option 133 [ iii ]