Hands-On Design Patterns with Kotlin Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin Alexey Soshin BIRMINGHAM - MUMBAI Hands-On Design Patterns with Kotlin 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: Richa Tripathi Acquisition Editor: Shriram Shekhar Content Development Editor: Zeeyan Pinheiro Technical Editor: Ketan Kamble Copy Editor: Safis Editing Project Coordinator: Vaidehi Sawant Proofreader: Safis Editing Indexer: Rekha Nair Graphics: Jason Monteiro Production Coordinator: Aparna Bhagat First published: June 2018 Production reference: 1130618 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78899-801-7 www.packtpub.com To Lula Leus, my constant source of inspiration. To my mentor, Lior Bar On. Without you, I would have never started writing. 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 built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content PacktPub.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.PacktPub.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.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. Contributors About the author Alexey Soshin is a software architect with 13 years of experience of making software, mostly for JVM. He started exploring Kotlin even before Kotlin 1.0 was released, and since then, he has been a big enthusiast of the language. He speaks about Kotlin and reactive frameworks at various conferences and meetups and maintains a technical blog. He's also a contributor to Vert.x, a toolkit for building reactive applications on the Java Virtual Machine. About the reviewers Ranga Rao Karanam is a programmer, trainer, and architect. He is the founder of in28Minutes—helping 200,000 learners reskill on Cloud native applications, microservices, evolutionary design, high-quality code, DevOps, BDD, TDD, and refactoring. He loves consulting for startups on the development of scalable component-based cloud-native applications and following modern development practices, such as BDD, continuous delivery, and DevOps. Ranga likes to play cricket and tennis, and he is a regular hiker. His dream is to spend a year hiking in the Himalayas. Ganesh Samarthyam is a co-founder of CodeOps Technologies, a software technology, consultancy, and training company based in Bangalore. He has 16 years of experience in the IT industry, and his latest book, Refactoring for Software Design Smells by Morgan Kaufmann/Elsevier, has been translated into Korean and Chinese. Ganesh loves exploring anything and everything about technology in his free time. 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: Getting Started with Kotlin 6 Basic language syntax and features 6 Multi-paradigm 7 Code structure 7 No semicolons 7 Naming conventions 8 Packages 8 Types 8 Type inference 8 val versus var 9 Comparison 9 Null safety 10 Declaring functions 11 Control flow 12 Using the if expression 13 Using the when expression 14 String interpolation 14 Classes and inheritance 15 Classes 15 Inheritance 16 Constructors 17 Properties 18 Data classes 19 More control flow – loops 20 The for loop 20 For-each loop 21 While loop 22 Extension functions 22 Introduction to design patterns 23 What are design patterns? 23 Design patterns in real life 24 Design process 24 Why use design patterns in Kotlin? 25 Summary 25 Chapter 2: Working with Creational Patterns 26 Singleton 26 Factory Method 28 Factory 28 Table of Contents Static Factory Method 33 Advantages of the Static Factory Method 33 Caching 33 Subclassing 33 Static Factory Method in Kotlin 34 Companion object 34 Abstract Factory 36 Abstract Factory in action 36 Introduction to generics in Kotlin 37 Back to our bases 39 Making improvements 41 Builder 43 Composing an email 43 Collection types in Kotlin 44 Creating an email – first attempt 44 Creating an email – second attempt 45 Creating an email – the Kotlin way 46 Creating an email – the Kotlin way – second attempt 47 Prototype 48 Building your own PC 48 Starting from a prototype 49 Summary 50 Chapter 3: Understanding Structural Patterns 51 Decorator 51 Enhancing a class 52 Operator overloading 53 Dude, where's my map? 55 The great combinator 55 Caveats 57 Adapter 58 Different adapters 59 Adapters in the real world 60 Caveats of using adapters 60 Bridge 61 Bridging changes 63 Type aliases 64 You're in the army now 64 Constants 65 A lethal weapon 65 Composite 66 Get together 66 The Squad 67 Varargs and secondary constructors 68 Counting bullets 69 Facade 71 Keep it simple 72 [ ii ] Table of Contents Flyweight 73 Being conservative 73 Saving memory 75 Proxy 76 A short detour into the RMI world 77 A replacement 77 Lazy delegation 78 Summary 79 Chapter 4: Getting Familiar with Behavioral Patterns 80 Strategy 81 Fruit arsenal 82 Citizen function 83 Switching sides 84 Iterator 85 One, two... many 85 Running through the values 86 State 89 Fifty shades of State 90 State of the Nation 92 Command 93 Undoing commands 97 Chain of responsibility 98 Interpreter 100 We need to go deeper 101 A language of your own 101 Taking a break 105 Call suffix 105 Mediator 106 Trouble in the Jungle 106 The middleman 109 Flavors 110 Caveats 110 Memento 111 Remembrance 111 Visitor 114 Writing a crawler 114 Template method 117 Observer 120 Animal Choir 121 Summary 125 Chapter 5: Functional Programming 126 Why functional programming? 126 Immutability 127 [ iii ]