Kotlin For Android Developers Sample
Kotlin For Android Developers Sample
Antonio Leiva
This book is for sale at http://leanpub.com/kotlin-for-android-developers
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook
using lightweight tools and many iterations to get reader feedback, pivot until you
have the right book and build traction once you do.
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.1 What is Kotlin? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 What do we get with Kotlin? . . . . . . . . . . . . . . . . . . . . . . . . . . 8
I. About this book
Hey! Thanks so much for your interest in this book, I am thrilled that you decided to
become a Kotlin for Android expert.
Many things have happened since I started writing “Kotlin for Android Developers”
in mid-2015. At that point, Kotlin was still in an early access edition. However, I
felt so much power in the language, that I decided to explain everything that I was
learning in a book.
Since then, the language has kept growing to the point that Google announced that
they would start supporting Kotlin as an official language to develop Android apps.
These were amazing news. But it was even more amazing that both Google and
JetBrains suggested this book to Android developers who want to learn the language.
As you may know, this is a lean publication. This book grew and progressed thanks
to the readers’ comments. So I can only thank you for helping me bring this dream
to life.
tools and libraries. However, this text covers most of the features of Kotlin, so by the
end of the reading, you will have an in-depth knowledge of the language.
The content is very practical, so I recommend that you follow the examples and the
code in front of a computer and try everything it suggests. You could, however, take
one first read to get a broad idea and then dive into practice.
Even though this book now finished, I will review it from time to time to keep it up
to date with new Kotlin versions. So feel free to write and tell me what you think
about the book, or what could be improved. I want this book to be the perfect tool
for Android developers, and as such, help and ideas will be welcomed.
If you are reading a printed copy and want to receive the latest updates, please feel
free to email me at [email protected] with a proof of purchase, and I will
give you access to the digital copy. That way, you will keep receiving the updates.
Do the same if you got it from any bookstores (Kindle, Kobo…) and you want to get
access to the PDF version.
Thanks for becoming part of this exciting project!
II. Is this book for you?
This book is written to be useful to Android developers who are interested in learning
the Kotlin language.
This book is for you if you are in some of the following situations:
• You have some basic knowledge of Android Development and the Android
SDK, as well as the Java language.
• You want to learn how to develop Android apps using Kotlin by following an
example.
• You need a guide on how to solve many of the common challenges Android
developers face every day, by using a cleaner and more expressive language.
On the other hand, this book may not be for you. These are the topics that you will
not find in it:
• The content of these pages is not a Kotlin Bible. I shall explain all language
basics, and even more complicated ideas when they come out during the
process, just when we need them. So you will learn by example and not the
other way round.
• I will not explain how to develop an Android app. You do not need a deep
understanding of the platform, but at least some basics, such as some knowledge
of Android Studio, Gradle, Java programming and Android SDK. You may even
learn some new Android things in the process!
• The book is not a guide to functional programming. Of course, I am showing
what you need, as Java 6 is not functional at all, but I will not dive deep into
the programming paradigm.
III. About the author
Hi! This is Antonio Leiva.
Since the end of 2018, I am self-employed. I spend my time helping Android
developers and the companies they work for to transition from Java to Kotlin. By
mastering the language, they manage to boost their productivity and create more
robust and maintainable software.
I am really thankful for having had the opportunity to help thousands of people with
my content, which goes from my regular posts in my blog antonioleiva.com to this
book you currently have in your hands.
I also became a Kotlin Certified Training by JetBrains, so I am proud to offer
certified training, which you or your company can participate in. I have both
online and live training. If you are interested in any of them, please write me to
[email protected]¹. As a valued customer, I can offer you huge discounts
on the online training².
If you want to know a little about me, I live in Madrid, Spain. I’ve been working as
a software developer for more than 10 years. I started as a CRM consultant, but at
some point, I found Android and quickly fell in love. Since that, I moved from my
first company to another one called Gigigo, a Spanish brand that built third-party
Apps.
Finally, I had the chance to join Plex³ and start working remotely. It was a vast and
challenging experience as an Android developer that helped me learn a lot of how a
software company works.
But in the meanwhile, the success of this book made me realize that there was a
considerable need wanting to be covered, so I started running my own business.
When our baby was born, my spare time was highly reduced, so I had to make a
¹mailto:[email protected]
²https://antonioleiva.com/online-course/
³https://plex.tv
III. About the author 5
decision. That led me to focus 100% on helping other Android developers boost their
careers.
On my free time, I just like enjoying all the little moments I can with my family. I
also love cooking, especially since I became vegan and had to reinvent the way I eat
every day. And of course, I enjoy new technologies and staying up to date as much
as I can in this sector.
If you want to keep in contact and know more about my day-to-day, you can follow
me on my different places:
• Blog: antonioleiva.com⁴
• Twitter: @lime_cl⁵
• Instagram: antonioleivag⁶
• Facebook Group: Kotlin for Android Developers⁷
• YouTube Channel: Tutorials & Interviews⁸
• LinkedIn: antoniolg⁹
• Kotlin is very intuitive and easy to learn for Java developers. Most parts of
the language are very similar to what we already know, and the differences can
be mastered in no time.
• We have total integration with our daily IDE for free. Android Studio
can understand, compile and run Kotlin code. Moreover, the support for this
language comes from the company who develops the IDE, so we Android
developers are first-class citizens.
However, this is only related to how the language integrates with our tools. What
are the advantages of the language when compared to Java 6?
• ** It is more expressive**: this is one of its main points. You can write more with
much less code.
• ** It is safer**: Kotlin is null safe, which means that we deal with possible null
situations at compile time, to prevent execution time exceptions. We need to
specify that an object can be null explicitly, and then check its nullity before
using it. You can save much time debugging null pointer exceptions and fixing
nullity bugs.
• ** It is functional**: Kotlin is fundamentally an object-oriented language, not a
pure functional language. However, like many other modern languages, it uses
many concepts from functional programming, such as lambda expressions, to
solve some problems more naturally. Another nice feature is the way it deals
with collections.
• It makes use of extension functions: This means we can extend any class with
new features even if we do not have access to the source code.
• ** It is highly interoperable**: You can continue using most libraries and code
written in Java because the interoperability between both languages is excellent.
It is even possible to create mixed projects, with both Kotlin and Java files
coexisting.
However, this is only the tip of the iceberg: - Since Kotlin 1.1, the final version of
Kotlin JS¹¹ was released. This new variant allows you to develop web apps using
Kotlin. - Since Kotlin 1.2, you can also create multiplatform projects¹². With it, you
¹¹https://kotlinlang.org/docs/reference/js-overview.html
¹²https://kotlinlang.org/docs/reference/whatsnew12.html#multiplatform-projects-experimental
1 Introduction 8
can share code between JVM and Javascript. - The JetBrains team has also released
Kotlin/Native¹³, a project that finally takes Kotlin out of the JVM. Thanks to it, you
will be able to implement the server, the web and the Android and iOS Apps using
Kotlin for most of the code base. - Gradle 5.0 has added support to Kotlin DSL (a
simplified version of Kotlin) to write Gradle files instead of Groovy. This is already
an official feature that you can start using today. You can read more in Gradle’s
blog¹⁴.
So you can see that the future of Kotlin is pretty promising. Learning Kotlin can
become the language of reference in many other platforms, and sharing code among
all them is undoubtedly a high selling point.
Expressiveness
With Kotlin, it is much easier to avoid boilerplate because the language covers the
most common patterns by default. For instance, in Java, if we want to create a data
class, we need to write (or at least generate) this code:
¹³https://kotlinlang.org/docs/reference/native-overview.html
¹⁴https://blog.gradle.org/kotlin-dsl-1.0
1 Introduction 9
13 }
14
15 public String getName() {
16 return name;
17 }
18
19 public void setName(String name) {
20 this.name = name;
21 }
22
23 public String getUrl() {
24 return url;
25 }
26
27 public void setUrl(String url) {
28 this.url = url;
29 }
30
31 public String getMbid() {
32 return mbid;
33 }
34
35 public void setMbid(String mbid) {
36 this.mbid = mbid;
37 }
38
39 @Override public String toString() {
40 return "Artist{" +
41 "id=" + id +
42 ", name='" + name + '\'' +
43 ", url='" + url + '\'' +
44 ", mbid='" + mbid + '\'' +
45 '}';
46 }
47 }
This data class auto-generates all the fields and property accessors, as well as some
useful methods such as toString(). You also get equals() and hashCode() for free,
which are very verbose and can be dangerous if they are incorrectly implemented.
Null Safety
When we use Java, a significant amount of our code is defensive. We need to check
once and another whether something is null before using it to prevent unexpected
NullPointerException. Kotlin, like many other modern languages, is null-safe because
the type explicitly defines whether an object can be null by using the safe call
operator (written ?).
We can do things like this:
Extension functions
Thanks to extension functions, you can add new functions to any class. It is a cleaner
substitute for the common utility classes we all have in our projects. You could, for
instance, add a new method to fragments to show a toast:
1 fragment.toast("Hello world!")
This set of features is only a small selection of what Kotlin can do to simplify your
code. Now that you know some of the many great features of the language, you may
decide that this is not for you. If you continue, we will start writing some code right
away in the next chapter.