Programming Kotlin [Englishonlineclub.Com].Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Programming Kotlin Familiarize yourself with all of Kotlin’s features with this in- depth guide Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Copyright © 2017 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 authors, 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: January 2017 Production reference: 1130117 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78712-636-7 www.packtpub.com Credits Authors Copy Editor Stephen Samuel Safis Editing Stefan Bocutiu Reviewers Project Coordinator Antonios Chalkiopoulos Vaidehi Sawant Alexander Hanschke Commissioning Editor Proofreader Aaron Lazar Safis Editing Acquisition Editor Indexer Kirk D'costa Tejal Daruwale Soni Sonali Vernekar Content Development Editor Graphics Nikhil Borkar Abhinash Sahu Technical Editor Production Coordinator Subhalaxmi Nadar Shraddha Falebhai About the Authors Stephen Samuel is an accomplished developer with over 17 years of experience. He has worked with Java throughout his career, and in the past 5 years has focused on Scala. He has a passion for concurrency and Big Data technologies. Having spent the last few years in investment banking, he is currently working with Kotlin on a major Big Data ingestment project. Stephen is also active in the open source community, being the author of several high profile Scala and Kotlin libraries. I would like to thank my wife for being patient with all the days and nights spent on the computer, developing. I would also like to thank Stefan for kindly agreeing to co-author this book with me. Stefan Bocutiu is a Big Data consultant with over 13 years of experience in software development. He enjoys coding in Scala, C#, and has a passion for stream processing technologies. With the team at DataMountaineer--a consultancy company offering delivery of solutions for streaming/ fast data platforms - he focuses on providing scalable, unified, real-time data pipelines allowing reactive decision making, analytics, and Hadoop integration. Stefan is passionate about motorsports, and while his racing skills are not good enough to allow him to compete, he tries to attend as many MotoGP races as possible. When he is not coding, he can be found at the climbing wall or at the gym. Occasionally, hiking and scrambling trips are on his calendar, and during the winter season, skiing trips are a must for him. About the Reviewers Antonios Chalkiopoulos is a distributed systems specialist, engineering Big Data systems in the past 5 years on Media, Betting, Retail, Investment Banks, and FinTech companies in London. He is the author of Programming MapReduce with Scalding, one of the first books presenting how Scala can be used for Big Data solutions, and an open source contributor to a number of projects. He is the founder of LANDOOP, a company that specializes in Fast Data and Big Data solutions and provides numerous tools and capabilities around Apache Kafka and real-time streaming systems. Alexander Hanschke is a co-founder and CTO at techdev Solutions GmbH, a software company based in Berlin. He graduated from University of Mannheim and has worked in the financial sector, building Java enterprise applications for 8 years. At his company, these days Alex is working on web applications written in Java and Kotlin. He frequently talks at user groups and conferences and is writing about Kotlin-related topics. You can find him on Twitter at @alexhanschke. www.PacktPub.com For support files and downloads related to your book, please visit www.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. h t t p s ://w w w . p a c k t p u b . c o m /m a p t Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser Customer Feedback Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected]. Table of Contents Preface 1 Chapter 1: Getting Started with Kotlin 7 Using the command line to compile and run Kotlin code 8 Kotlin runtime 10 The REPL 10 Kotlin for scripting 11 Kotlin with Gradle 12 Kotlin with Maven 15 IntelliJ and Kotlin 18 Eclipse and Kotlin 22 Mixing Kotlin and Java in a project 24 Summary 29 Chapter 2: Kotlin Basics 30 Vals and vars 30 Type inference 31 Basic types 32 Numbers 32 Booleans 33 Chars 34 Strings 34 Arrays 34 Comments 35 Packages 36 Imports 36 Wildcard imports 36 Import renaming 37 String templates 37 Ranges 38 Loops 39 Exception handling 40 Instantiating classes 41 Referential equality and structural equality 42 This expression 43 Scope 43 Visibility modifiers 43 Private 44 Protected 44 Internal 45 Control flow as expressions 45 Null syntax 46 Smart casts 47 Explicit casting 48 When expression 49 When (value) 49 When without argument 51 Function Return 52 Type hierarchy 53 Summary 54 Chapter 3: Object-Oriented Programming in Kotlin 55 Classes 56 Access levels 60 Nested classes 60 Data classes 63 Enum classes 63 Static methods and companion objects 64 Interfaces 69 Inheritance 73 Visibility modifiers 76 Abstract classes 78 Interface or abstract class 79 Polymorphism 79 Overriding rules 85 Inheritance versus composition 87 Class delegation 89 Sealed classes 91 Summary 92 Chapter 4: Functions in Kotlin 93 Defining functions 93 Single expression functions 94 Member functions 95 Local functions 95 Top-level functions 98 [ ii ] Named parameters 99 Default parameters 100 Extension functions 103 Extension function precedence 105 Extension functions on nulls 106 Member extension functions 106 Overriding member extension functions 107 Companion object extensions 109 Multiple return values 110 Infix functions 111 Operators 113 Operator overloading 114 Basic operators 115 In/contains 116 Get/set 117 Invoke 117 Comparison 118 Assignment 119 Java interop 120 Function literals 120 Tail recursive functions 121 Varargs 123 Spread operator 124 Standard library functions 124 Apply 125 Let 126 With 126 Run 126 Lazy 127 Use 127 Repeat 128 Require/assert/check 128 Generic functions 129 Pure functions 130 Java from Kotlin 131 Getters and setters 131 Single abstract methods 132 Escaping Kotlin identifiers 133 Java void methods 133 [ iii ] Kotlin from Java 134 Top-level functions 134 Default parameters 135 Object and static methods 135 Erasure naming 136 Checked exceptions 136 Summary 137 Chapter 5: Higher Order Functions and Functional Programming 138 Higher order functions 138 Returning a function 140 Function assignment 141 Closures 142 Anonymous functions 143 Function references 144 Top-level function references 144 Member and extension function references 144 Bound references 145 Function-literal receivers 146 Functions in the JVM 147 Bytecode 148 Function composition 149 Inline functions 151 Noinline 155 Currying and partial application 156 Currying in action 157 Adding currying support 158 Memoization 159 Implementing memoization 161 Type alias 162 Either 164 Fold 164 Projection 165 Further projection functions 167 Custom DSLs 169 Infix functions as keywords 170 Using function receivers in a DSL 173 Validation and error accumulation 174 Summary 177 [ iv ] Chapter 6: Properties 178 Why use properties? 178 Syntax and variations 181 Visibility 183 Late initialization 184 Delegated properties 185 Lazy initializations 191 Lateinit versus lazy 196 Observables 197 A non-null property delegate 198 Properties or methods? 198 Summary 200 Chapter 7: Null Safety, Reflection, and Annotations 201 Nullable types 202 Smart cast 203