Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Kotlin Essentials MarcinMoskała This book is for sale at http://leanpub.com/kotlin_developers This versionwas published on 2022-12-15 ISBN 978-83-966847-0-7 This is a Leanpub book. Leanpub empowers authors and publisherswith the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2022MarcinMoskała
Page
3
Contents Introduction 1 Forwhom is this bookwritten? 1 Whatwill be covered? 1 TheKotlin for Developers series 2 My story 3 Conventions 3 Code conventions 4 Acknowledgments 5 What is Kotlin? 7 Kotlin platforms 7 TheKotlin IDE 11 Where dowe use Kotlin? 11 Your first program inKotlin 13 Live templates 15 What is under the hood on JVM? 16 Summary 19 Variables 20 Basic types, their literals, and operations 24 Numbers 24 Booleans 35 Characters 37 Strings 38 Summary 41 Conditional statements: if, when, try, andwhile 43 if-statement 43 when-statement 49 when-statementwith a value 51 is check 53 Explicit casting 54
Page
4
CONTENTS Smart-casting 56 While and do-while statements 58 Summary 60 Functions 61 Single-expression functions 64 Functions on all levels 65 Parameters and arguments 67 Unit return type 68 Vararg parameters 69 Named parameter syntax and default arguments 71 Function overloading 73 Infix syntax 74 Function formatting 76 Summary 80 The power of the for-loop 81 Ranges 83 Break and continue 85 Use cases 86 Summary 90 Nullability 91 Safe calls 92 Not-null assertion 94 Smart-casting 95 The Elvis operator 96 Extensions on nullable types 98 null is our friend 100 lateinit 101 Summary 103 Classes 104 Member functions 104 Properties 106 Constructors 113 Classes representing data in Kotlin and Java 117 Inner classes 118 Summary 120 Inheritance 121 Overriding elements 122 Parentswith non-empty constructors 123 Super call 124
Page
5
CONTENTS Abstract class 125 Interfaces 128 Visibility 134 Any 140 Summary 140 Data classes 142 Transforming to a string 145 Objects equality 147 Hash code 148 Copying objects 149 Destructuring 152 When and how shouldwe use destructuring? 153 Data class limitations 155 Prefer data classes instead of tuples 156 Summary 160 Objects 162 Object expressions 162 Object declaration 166 Companion objects 167 Data object declarations 174 Constant values 175 Summary 176 Exceptions 178 Throwing exceptions 179 Defining exceptions 180 Catching exceptions 181 Try-catch block used as an expression 182 Finally block 184 Important exceptions 185 Hierarchy of exceptions 187 Summary 188 Enum classes 189 Data in enumvalues 192 Enum classes with custommethods 193 Summary 194 Sealed classes and interfaces 195 Sealed classes and when expressions 197 Sealed vs enum 199 Use-cases 199
Page
6
CONTENTS Summary 201 Annotation classes 202 Meta-annotations 204 Annotating primary constructor 205 List literals 205 Summary 206 Extensions 207 Extension functions under the hood 209 Extension properties 211 Extensions vsmembers 212 Extension functions on object declarations 215 Member extension functions 216 Use-cases 217 Summary 222 Collections 223 The hierarchy of interfaces 224 Mutable vs read-only types 225 Creating collections 227 Lists 229 Sets 235 Maps 240 Using arrays in practice 246 Summary 253 Operator overloading 254 An example of operator overloading 255 Arithmetic operators 256 The rangeUntil operator 257 The in operator 258 The iterator operator 259 The equality and inequality operators 261 Comparison operators 262 The indexed access operator 264 Augmented assignments 265 Unary prefix operators 267 Increment and decrement 268 The invoke operator 269 Precedence 270 Summary 272 The beauty of Kotlin’s type system 273
Page
7
CONTENTS What is a type? 273 Why dowe have types? 275 The relation between classes and types 277 Class vs type in practice 277 The relationship between types 279 The subtype of all the types: Nothing 282 The result type from return and throw 284 When is some code not reachable? 287 The type of null 289 Summary 291 Generics 292 Generic functions 293 Generic classes 295 Generic classes and nullability 297 Generic interfaces 298 Type parameters and inheritance 301 Type erasure 303 Generic constraints 304 Star projection 306 Summary 308 Final words 309
Page
8
Introduction 1 Introduction Kotlin is a powerful language, largely thanks to its expressive syntax, intuitive and null-safe type system, and great tooling support. It’s no wonder Kotlin is the most popular language for Android development and is a popular alternative to Java for backend applications. It is also used for data science and for multiplatform, iOS, desktop, and web application devel- opment. In this book, you are going to learn about the most important Kotlin features, which will let you properly start your adventurewith Kotlin. For whom is this book written? This book is dedicated to developers. I assume that all devel- opers understand what functions, if-statements, or strings are. However, I try to explain (at least briefly) all the topics thatmight not be clear for all kinds of developers, like classes, enums, or lists. So I assume this book might be read by C, JavaScript, orMatlab developers. Kotlin is a multiplatform language, but it is mainly used on JVM. Also, most Kotlin developers have experience in Java. This is why I sometimes reference Java and its platform, and I sometimes present JVM-specific elements. Whenever I do this, I state it explicitly. I assume that some readers might be mainly interested in using Kotlin/JS or Kotlin/Native, so everything that is not described as Java-specific should be useful for them. What will be covered? In this book, I cover the topics that I find essential for pro- gramming in Kotlin, including: • variables, values, and types, • conditional statements and loops,
Page
9
Introduction 2 • support for nullability, • classes, interfaces, and inheritance, • object expressions and declarations, • data, sealed, enum, and annotation classes, • exceptions, • extension functions, • collections, • operator overloading, • the type system, • generics. This book does not cover functional Kotlin features, like lambda expressions or function types. All the functional features are covered in the continuation of this book: Functional Kotlin. The Kotlin for Developers series This book is the first in a series of books called Kotlin for Developers, which includes the following books: • Kotlin Essentials. This covers all the basic Kotlin fea- tures. • FunctionalKotlin.This is dedicated to functionalKotlin features, including function types, lambda expressions, collection processing, DSLs, and scope functions. • Advanced Kotlin. This is dedicated to advanced Kotlin features, including generic variance modifiers, delega- tion, documenting code, string processing, reflection, andmultiplatformprogramming. This book and my two other books, Kotlin Coroutines and Effective Kotlin, make a big series covering everything that I believe is needed to become an amazing Kotlin developer.
Page
10
Introduction 3 My story My story with Kotlin started in 2015 when I worked as a Java Android developer. I was quite frustrated with all the boilerplate code, like getters and setters for every field, and the nearly identical equals, toString, and hashCode methods that are often repeated in many classes. Then, I found the Kotlin preview on the JetBrains website, and I became so fascinated that I dedicated every free moment to exploring this language. Soon after that, I got a job in Kotlin develop- ment and became immersed in the community. Now, I have been professionally using Kotlin for over seven years, during which I have published hundreds of articles about Kotlin and a bunch of books, and I have conducted over a hundred workshops about Kotlin. I have become an official JetBrains partner for teaching Kotlin, and a Google Developer Expert in Kotlin. I accumulated a lot of knowledge during all these experiences, so I decided to express it in the formof a series of books, which I callKotlin for Developers. Conventions When I mean a concrete element from code, I will use code font. To name a concept, I will use uppercase. To reference an arbitrary element of some type, I will use lowercase. For example: • List is a type or an interface, so it is printed in code font (as in “Function needs to return List”), • List represents a concept, so it starts with uppercase (as in “This explains the essential difference between List and Set”), • a list is an instance, which is why it is lowercase (as in “the list variable holds a list”). In this book, I decided to use a dash between “if”, “when”, “try”, “while”, and “for”, and the word describing it, like “condition”, “loop”, “statement”, or “expression”. I do this to
Page
11
Introduction 4 improve readability. So, I will write “if-condition” instead of “if condition”, or “while-loop” instead of “while loop”. “if” and“when”are conditions, “while” and“for” are loops.All of them can be used as statements, while “if”, “when” and “try” canalsobeusedasexpressions. I alsodecidednot touseadash after “if-else”, “if-else-if”, or “try-catch” and their descriptor, like in an “if-else statement”. Code conventions Most of the presented snippets are executable code with no import statements. In the online version of this book on the Kt. Academy website, most snippets can be executed so that readers can playwith the code. Snippet results are presented using the println function. The result will often be placed after the statement. Here is an example: fun main() { println("Hello") // Hello println(10 + 20) // 30 }
Page
12
Introduction 5 Acknowledgments Owen Griffiths has been developing soft- ware since the mid 1990s and remembers theproductivityof languages suchasClip- per and Borland Delphi. Since 2001, he hasmoved toweb, server-based Java, and the open-source revolution. With many years of commercial Java experience, he picked up Kotlin in early 2015. After taking detours into Clojure and Scala, like Goldilocks, he thinks Kotlin is just right and tastes the best. Owen enthusiastically helps Kotlin developers continue to succeed. Nicola Corti is a Google Developer Ex- pert for Kotlin. He has been working with this language since before version 1.0 and is the maintainer of several open- source librariesandtools formobiledevel- opers (Detekt, Chucker, AppIntro). He’s currently working in the React Native core team at Meta, building one of the most popular cross- platform mobile frameworks. Furthermore, he is an active member of the developer community. His involvement goes from speaking at international conferences to being a mem- ber of CFP committees and supporting developer commu- nities across Europe. In his free time, he also loves baking, podcasting, and running. Matthias Schenk started his career with Java over ten years ago, mainly in the Spring/Spring Boot Ecosystem. Eighteen monthsago,heswitchedtoKotlinandhas since become a big fan of working with native Kotlin frameworks like Koin, Ktor, and Exposed.
Page
13
Introduction 6 Endre Deak is a software architect build- ing AI infrastructure at Disco, a market- leading legal tech company. He has 15 years of experiencebuilding complex scal- able systems, and he thinks Kotlin is one of the best programming languages ever created. Emanuele Papa is passionate about An- droid and has been fascinated by it since 2010: the more he learns, the more he wants to share his knowledgewith others, which is why he started his own blog. In his current role as Senior Android Devel- oper at Zest One, he is now focusing on KotlinMultiplatformMobile: he has already given a few talks on this topic. Roman Kamyshnikov, PhD in engineering, is an Android developer who started his career with Java but switched to Kotlin at the beginning of 2020. His professional interests in- clude architecture patterns, TDD, functional programming, and Jetpack Compose. Author of several articles about An- droid andKotlin Coroutines. Grigory Pletnev has been a software engineer since 2000, mostly in theembeddeddomain.He joined theAndroiddevel- oper community in 2010. Having got acquainted with Kotlin in 2017, he began to use it in pet projects, graduallymigrating Harman Connected Services and its customers’ projects to Kotlin. He also has a passion for languages, sailing, andmead making.
Page
14
What is Kotlin? 7 What is Kotlin? Kotlin is an open-source, multiplatform, multi-paradigm, statically typed, general-purpose programming language. Butwhat does all thismean? • Open-source means that the sources of the Kotlin com- piler are freely available for modification and redistri- bution. Kotlin is primarily made by JetBrains, but now there is the Kotlin Foundation, which promotes and advances thedevelopmentof this language.There isalso a public process known as KEEP, which allows anyone to see and comment on official design change proposi- tions. • Multiplatform means that a language can be used on more than one platform. For instance, Kotlin can be used both onAndroid and iOS. • Multi-paradigm means that a language has support for more thanoneprogrammingparadigm.Kotlinhas pow- erful support for both Object-Oriented Programming and Functional Programming. • Statically typed means that each variable, object, and functionhas anassociated type that is knownat compile time. • General-purposemeans thata language isdesigned tobe used for building software in a wide variety of applica- tion domains across amultitude of hardware configura- tions and operating systems. These descriptions might not be clear now, but you will see them all in action throughout the book. Let’s start by dis- cussing Kotlin’smultiplatform capabilities. Kotlin platforms Kotlin is a compiled programming language.Thismeans that you can write some code in Kotlin and then use the Kotlin
Page
15
What is Kotlin? 8 compiler to produce code in a lower-level language. Kotlin can currently be compiled into JVM bytecode (Kotlin/JVM), JavaScript (Kotlin/JS), ormachine code (Kotlin/Native). In this book, I would like to address all these compilation targets and, by default, show code that works on all of them, but I will concentrate on themost popular one: Kotlin/JVM. Kotlin/JVM is the technology that’s used to compile Kotlin code into JVM bytecode. The result is nearly identical to the result of compiling Java code into JVM bytecode. We also use the term “Kotlin/JVM” to talk about code that will be compiled into JVMbytecode.
Page
16
What is Kotlin? 9 Kotlin/JVM and Java are fully interoperable. Any code writ- ten in Java can be used in Kotlin/JVM. Any Java library, including those based on annotation processing, can be used in Kotlin/JVM. Kotlin/JVM can use Java classes, modules, libraries, and theJava standard library.AnyKotlin/JVMcode can be used in Java (except for suspending functions, which are a support for Kotlin Coroutines). Kotlin and Java can bemixed in a single project. A typical sce- nario is that aprojectwas initiallydeveloped inJava, but then its creators decided to start using Kotlin. To do this, instead of migrating the whole project, these developers decided to
Page
17
What is Kotlin? 10 add Kotlin to it. So, whenever they add a new file, it will be a Kotlin file; furthermore, when they refactor old Java code, they will migrate it to Kotlin. Over time, there is more and more Kotlin code until it excludes Java completely. One example of such a project is the Kotlin compiler itself. It was initiallywritten inJava, butmore andmore filesweremi- grated to Kotlin when it became stable enough. This process has been happening for years now; at the time ofwriting this book, theKotlin compiler project still contains around 10%of Java code. Now thatweunderstand the relationshipbetweenKotlin and Java, it is time to fight somemisconceptions.Many seeKotlin as a layer of syntactic sugar on top of Java, but this is not true. Kotlin is a different language than Java. It has its own conventions and practices, and it has features that Java does not have, likemultiplatform capabilities and coroutines. You don’t need to knowJava to understandKotlin. Inmyopinion, Kotlin is a better first language than Java. Junior Kotlin developers do not need to know what the equals method is and how to override it. For them, it is enough to know the default class anddata class equality¹. Theydon’t need to learn to write getters and setters, or how to implement a singleton or a builder pattern. Kotlin has a lower entry threshold than ¹It will be explained in the chapterData classes.
Page
18
What is Kotlin? 11 Java and does not need the JVMplatform. The Kotlin IDE The most popular Kotlin IDEs (integrated development envi- ronments) are IntelliJ IDEA and Android Studio. However, you can alsowrite programs in Kotlin using VSCode, Eclipse, Vim, Emacs, Sublime Text, and many more. You can also write Kotlin code online, for instance, using the official on- line IDE that can be found at this link play.kotlinlang.org. Where do we use Kotlin? Kotlin can be used as an alternative to Java, JavaScript, C++, Objective-C, etc. However, it is most mature on JVM, so it is currentlymainly used as an alternative to Java. Kotlin has become quite popular for backend development. I most often see it used with the Spring framework, but some projects use Kotlin with backend frameworks like Vert.x, Ktor,Micronaut, http4k or Javalin. Kotlin has also practically become the standard language for Android development.Google has officially suggested that all Android applications should be written in Kotlin² and has announced that all their APIs will be designed primarily for Kotlin³. More andmore projects are now taking advantage of the fact that Kotlin can be compiled for a few different platforms be- cause thismeans that teams canwrite code that runs on both Android and iOS, or on both the backend and the frontend. Moreover, this cross-platform compatibility means that li- brary creators cancreateone library formultipleplatformsat the same time.Kotlin’smultiplatformcapabilities are already ²Source: https://techcrunch.com/2022/08/18/five-years- later-google-is-still-all-in-on-kotlin/ ³Source: https://developer.android.com/kotlin/first
Page
19
What is Kotlin? 12 beingused inmanycompanies, and theyaregettingmoreand more popular. It is also worth mentioning Jetpack Compose, which is a toolkit for building native UIs in Kotlin. It was initially devel- oped for Android, but it uses Kotlin’s multiplatform capabili- ties and can also be used to create views forwebsites, desktop applications, iOS applications, and other targets⁴. A lot of developers are using Kotlin for front-end develop- ment,mainlyusingReact, and there is also agrowingcommu- nity of data scientists using Kotlin. As you can see, there is already a lot that you can do in Kotlin, and there aremore andmorepossibilities as eachyear passes. I am sure you will find good ways to apply your new knowledge once you’ve finished reading this book. ⁴At themoment, thematurity of these targets differs.
Page
20
Your first program in Kotlin 13 Your first program in Kotlin The first step in our Kotlin adventure is to write a minimal program in this language. Yes, it’s the famous “Hello,World!” program. This is what it looks like in Kotlin: fun main() { println("Hello, World") } This is minimal, isn’t it? We need no classes (like we do in Java), no objects (like console in JavaScript), and no condi- tions (like in Pythonwhenwe start code in the IDE).We need the main function and the println function call with some text⁵. This is the most popular (but not the only) variant of the “main” function. If we need arguments, we might include a parameter of type Array<String>: fun main(args: Array<String>) { println("Hello, World") } There are also other forms of the main function: fun main(vararg args: String) { println("Hello, World") } ⁵The println function is implicitly imported from the stan- dard library package kotlin.io.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A practical, example-driven tour of Kotlin’s core language features for developers who want to write idiomatic Kotlin rather than Java-with-new-syntax. Best suited to programmers with some prior experience who want a structured foundation before moving on to advanced or multiplatform work.
【Book Arc】
- **Opening (~0%–10%)**: Positions Kotlin as a distinct language rather than “syntactic sugar on Java,” introduces tooling and the first program, and sets expectations for readers coming from Java or other backgrounds.
- **Early (~10%–30%)**: Builds the fundamentals — basic types, literals, operators, strings, conditionals (`if`, `when`, `try`, loops), functions (default/vararg/infix parameters), and Kotlin’s nullability model including smart-casting and `lateinit`.
- **Middle (~30%–55%)**: Moves into object-oriented Kotlin: classes, properties and encapsulation, inheritance and `open`/`override`, interfaces with default implementations, visibility modifiers, and data classes with `equals`/`hashCode`/`copy`/destructuring.
- **Late (~55%–80%)**: Extends the language surface with annotations and meta-annotations, extension functions and properties (including member extensions), the collections hierarchy and mutable vs read-only types, and operator overloading conventions.
- **Ending (~80%–100%)**: Closes with Kotlin’s type system as a unifying theme, tying together nullability, generics, and the design choices that distinguish Kotlin from Java. (Excerpts do not cover the final chapters in detail.)
【Book Arc note】
The progression is deliberately fundamentals → object model → language extensions → type-system synthesis, with each stage building on the previous one rather than presenting isolated features.
【Key Takeaways】
- **Kotlin is not Java with sugar** (Opening): The book argues Kotlin has its own conventions, features like coroutines and multiplatform, and a lower entry threshold — you don’t need Java to learn it. This framing matters because it shapes how you should read every later chapter.
- **Nullability is a first-class design concern** (Early): Safe calls, smart-casting after null checks, `requireNotNull`/`checkNotNull`, and `lateinit` for injected properties form a coherent toolkit. Treat `null` as meaningful (“unknown result”) rather than a defect.
- **Control flow is expression-oriented** (Early): `if`, `when`, and `try` are expressions; there is no `switch`, and “if-else-if” is really nested `if-else`. Understanding this prevents subtle bugs like the `printNumberSign` puzzle.
- **Functions carry more weight than in Java** (Early): Default arguments, `vararg`, named arguments, infix notation, and trailing commas reduce boilerplate and improve call-site readability. Overloading is presented as a convenience tool, not a default.
- **Classes are concise but explicit** (Middle): Properties with getters/setters replace public fields; `open`/`override` are required for inheritance; interfaces can hold default implementations, with `super<Interface>` resolving conflicts. Encapsulation is treated as a design principle, not syntax.
- **Data classes eliminate boilerplate** (Middle): `data` generates `equals`, `hashCode`, `toString`, `copy`, and destructuring. The book recommends custom data classes over `Pair`/`Triple` and warns about destructuring order mistakes.
- **Extensions are powerful but not magic** (Late): Extension functions/properties compile to static utilities and do not override members; member extensions and object-declaration extensions have specific use cases. Knowing the “under the hood” behavior prevents surprises.
- **Collections and operators follow conventions** (Late): The read-only vs mutable interface hierarchy, standard creation functions, and operator overloading (arithmetic, `in`, `iterator`, indexing, `invoke`) are presented as a coherent convention system rather than ad-hoc tricks.
【Reading Tips】
- **Skim the opening framing chapters** if you already know why Kotlin exists; slow down at nullability and smart-casting, which are the most error-prone fundamentals.
- **Deep-read the classes/inheritance/data-class block (~30%–55%)** — this is where Java habits most often produce non-idiomatic Kotlin.
- **Treat operator overloading and extensions as reference material**: read once for concepts, then return when you encounter them in real code.
- **Do the small code puzzles** (e.g., the `if-else-if` example) — they expose misconceptions faster than prose.
- **Take away a mental checklist**: prefer expressions, use data classes for value objects, design nullability intentionally, and reach for extensions only when members aren’t appropriate.
【Coverage Limits】
This guide is based on stratified excerpts covering roughly the first half of the book in detail, with lighter coverage of later chapters on annotations, extensions, collections, operator overloading, and the type system. Coroutines, multiplatform, and testing chapters are not represented in the excerpts and are not assessed here.
Passage locations
Page 12
thermore, he is an active member of the developer community. His involvement goes from speaking at international conferences to being a mem- ber of CFP commi...
View in text
Excerpt 2
ly, 123 is not of type String, and "ABC" is not of type Int.We can confirm this using the is check. fun main() { println(123 is Int) // true println("ABC" is...
View in text
Excerpt 3
getter - the function that is used to get the current value of this field, • setter - the function that isused to setnewvalues for this field. This pattern i...
View in text
Excerpt 4
ider the following class A, which is equal Data classes 149 To learnmore about thehash table algorithmand implement- ing a custom hashCode method, see Effect...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay