Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-16

AuthorAntonio Leiva

Learn Kotlin the easy way while developing an Android App. Kotlin is the new official language to write Android Apps, and thanks to this book, you'll be writing code in no time. Straight to the point, practical and full of examples, it will show you the language while developing an Android App. Learn the Kotlin and start enjoying Android development again with this powerful and modern language.

Tags
No tags
Publisher: Leanpub
Publish Year: 2017
Language: 英文
Pages: 191
File Format: PDF
File Size: 1.1 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
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.

(This page has no text content)
Kotlin for Android Developers Learn Kotlin the easy way while developing an Android App Antonio Leiva This book is for sale at http://leanpub.com/kotlin-for-android-developers This version was published on 2017-06-20 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. © 2015 - 2017 Antonio Leiva
Tweet This Book! Please help Antonio Leiva by spreading the word about this book on Twitter! The suggested hashtag for this book is #kotlinandroiddev. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#kotlinandroiddev
This book is dedicated to all the loyal readers of antonioleiva.com, who made me believe that writing about Android development was a powerful tool to help others learn about it. I felt this book as a necessary step forward. I also want to do a special mention to Luis Herrero Jiménez, who has designed the awesome cover of this book, and to Gautier Mechling for helping me so much by reviewing this book. It’s thanks to him that this pages are not full of typos and mistakes. And, of course, this is specially dedicated to you. With your support and your help this book is growing, and I hope it will become a reference. So any claim or suggestion you think it will improve the quality of this book will be welcomed. Feel free to write anytime to contact@antonioleiva.com.
Contents I. About this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What is “Kotlin for Android Developers” about . . . . . . . . . . . . . . 1 II. Is this book for you? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 III. About the author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.1 What is Kotlin? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 What do we get with Kotlin? . . . . . . . . . . . . . . . . . . . . . . 6 2 Getting ready . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.1 Android Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Install Kotlin plugin . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3 Creating a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.1 Create a new project in Android Studio . . . . . . . . . . . . . . . . 13 3.2 Convert MainActivity to Kotlin code . . . . . . . . . . . . . . . . . . 14 3.3 Configure Kotlin in project . . . . . . . . . . . . . . . . . . . . . . . 14 3.4 Include some other useful configuration . . . . . . . . . . . . . . . . 15 3.5 Test that everything works . . . . . . . . . . . . . . . . . . . . . . . 17 4 Classes and functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.1 How to declare a class . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.2 Class inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4.4 Constructor and functions parameters . . . . . . . . . . . . . . . . . 21
CONTENTS 5 Writing your first class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1 Creating the layout . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.2 The Recycler Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . 25 6 Variables and properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 6.1 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 6.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 6.3 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 7 Anko and Extension Functions . . . . . . . . . . . . . . . . . . . . . . . 33 7.1 What is Anko? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 7.2 Start using Anko . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 7.3 Extension functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 8 Retrieving data from API . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 8.1 Performing a request . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 8.2 Performing the request out of the main thread . . . . . . . . . . . . . 37 9 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 9.1 Extra functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 9.2 Copying a data class . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 9.3 Mapping an object into variables . . . . . . . . . . . . . . . . . . . . 40 10 Parsing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 10.1 Converting json to data classes . . . . . . . . . . . . . . . . . . . . . 42 10.2 Shaping the domain layer . . . . . . . . . . . . . . . . . . . . . . . 44 10.3 Drawing the data in the UI . . . . . . . . . . . . . . . . . . . . . . . 46 11 Operator overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 11.1 Operators tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 11.2 An example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 11.3 Operators in extension functions . . . . . . . . . . . . . . . . . . . . 51 12 Making the forecast list clickable . . . . . . . . . . . . . . . . . . . . . . 52 13 Lambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 13.1 Simplifying setOnClickListener() . . . . . . . . . . . . . . . . . . . 57
CONTENTS 13.2 Click listener for ForecastListAdapter . . . . . . . . . . . . . . . . . 59 13.3 Extending the language . . . . . . . . . . . . . . . . . . . . . . . . . 59 14 Visibility Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 14.1 Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 14.2 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 14.3 Reviewing our code . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 15 Kotlin Android Extensions . . . . . . . . . . . . . . . . . . . . . . . . . 65 15.1 How to use Kotlin Android Extensions . . . . . . . . . . . . . . . . 65 15.2 Refactoring our code . . . . . . . . . . . . . . . . . . . . . . . . . . 67 16 Application Singleton and Delegated Properties . . . . . . . . . . . . . 70 16.1 Application Singleton . . . . . . . . . . . . . . . . . . . . . . . . . . 70 16.2 Delegated Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 71 16.3 Standard Delegates . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 16.4 How to create a custom delegate . . . . . . . . . . . . . . . . . . . . 76 16.5 Reimplementing App Singleton . . . . . . . . . . . . . . . . . . . . 77 17 Creating an SQLiteOpenHelper . . . . . . . . . . . . . . . . . . . . . . . 79 17.1 ManagedSqliteOpenHelper . . . . . . . . . . . . . . . . . . . . . . . 79 17.2 Tables definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 17.3 Implementing SqliteOpenHelper . . . . . . . . . . . . . . . . . . . . 81 17.4 Dependency injection . . . . . . . . . . . . . . . . . . . . . . . . . . 84 18 Collections and functional operations . . . . . . . . . . . . . . . . . . . 86 18.1 Aggregate operations . . . . . . . . . . . . . . . . . . . . . . . . . . 87 18.2 Filtering operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 18.3 Mapping operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 18.4 Elements operations . . . . . . . . . . . . . . . . . . . . . . . . . . 93 18.5 Generation operations . . . . . . . . . . . . . . . . . . . . . . . . . 96 18.6 Ordering operations . . . . . . . . . . . . . . . . . . . . . . . . . . 97 19 Saving and requesting data from database . . . . . . . . . . . . . . . . 99 19.1 Creating database model classes . . . . . . . . . . . . . . . . . . . . 99 19.2 Writing and requesting data . . . . . . . . . . . . . . . . . . . . . . 101
CONTENTS 20 Null safety in Kotlin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 20.1 How Null types work . . . . . . . . . . . . . . . . . . . . . . . . . . 108 20.2 Nullity and Java libraries . . . . . . . . . . . . . . . . . . . . . . . . 111 21 Creating the business logic to data access . . . . . . . . . . . . . . . . . 112 22. Flow control and ranges . . . . . . . . . . . . . . . . . . . . . . . . . . 118 22.1 If Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 22.2 When expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 22.3 For loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 22.4 While and do/while loops . . . . . . . . . . . . . . . . . . . . . . . 121 22.5 Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 23 Creating a Detail Activity . . . . . . . . . . . . . . . . . . . . . . . . . . 124 23.1 Preparing the request . . . . . . . . . . . . . . . . . . . . . . . . . . 124 23.2 Providing a new activity . . . . . . . . . . . . . . . . . . . . . . . . 127 23.3 Start an activity: reified functions . . . . . . . . . . . . . . . . . . . 131 24 Interfaces and Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . 133 24.1 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 24.2 Delegation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 24.3 Implementing an example in our App . . . . . . . . . . . . . . . . . 135 25 Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 25.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 25.2 Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 25.3 Generics examples . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 26 Settings Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 26.1 Creating the settings activity . . . . . . . . . . . . . . . . . . . . . . 150 26.2 Accessing Shared Preferences . . . . . . . . . . . . . . . . . . . . . 152 26.3 Generic preference delegate . . . . . . . . . . . . . . . . . . . . . . 155 27 A first walk into coroutines . . . . . . . . . . . . . . . . . . . . . . . . . 158 27.1 Understanding how coroutines work . . . . . . . . . . . . . . . . . 158 27.2 Using Anko for coroutines . . . . . . . . . . . . . . . . . . . . . . . 160 27.3 Using coroutines in our example . . . . . . . . . . . . . . . . . . . . 162
CONTENTS 28 Testing your App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 28.1 Unit testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 28.2 Mocking closed classes . . . . . . . . . . . . . . . . . . . . . . . . . 169 28.3 Instrumentation tests . . . . . . . . . . . . . . . . . . . . . . . . . . 171 29 Extra concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 29.1 Nested classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 29.2 Enum classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 29.3 Sealed classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 29.4 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 30 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
I. About this book Hey! Thanks so much for your interest on this book, I’m really glad 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. But I felt so much power in the language, that I decided to explain all what 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 that want to learn the language. As you may know, this is a lean publication. This means that the book grew and progressed thanks to the readers comments. So I can only thank you for helping me bring this dream to life. What is “Kotlin for Android Developers” about In this book, I’ll be creating an Android app from ground up using Kotlin as the main language. The idea is to learn the language by example, instead of following a regular reference book structure. I’ll be stopping to explain the most interesting concepts and ideas about Kotlin, comparing them to Java 6. This way, you can see what the differences are and which parts of the language will help you speed up your work. This book is not meant to be a language reference, but a tool for Android developers to learn Kotlin and be able to continue with their own projects by themselves. I’ll be solving many of the most recurring problems we have to face in our daily lives as App developers, by making use of Kotlin expressiveness and some other really
I. About this book 2 interesting tools and libraries. However, this text covers most Kotlin features, so by the end of the reading you will have a deep knowledge about the language. The content is very practical, so I recommend you to follow the examples and the code in front of a computer and try everything it’s suggested. You could, however, take a 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 write me back to contact@antonioleiva.com with a proof of purchase, and I’ll give you access to the digital copy. That way, you’ll keep receiving the updates. 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 Kotlin language. This book is for you if you are in some of the following situations: • You have some basic knowledge about Android Development and the Android SDK, as well as 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 find every day, by using a cleaner and more expressive language. On the other hand, this book may not be for you. This is what you won’t find in it: • This is not a Kotlin Bible. I’ll explain all language basics, and even more complex 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 won’t need a deep un- derstanding 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! • This is not a guide to learn functional programming. Of course, I’ll explain what you need, as Java 6 is not functional at all, but I won’t dive deep into functional topics.
III. About the author Antonio Leiva is an Android Engineer who spends time learning about new ways to get the most out of Android and then writes about it. He writes a blog at antonioleiva.com1, focused in helping other Android developers learn Kotlin. He also leads intensive live workshops, where all the information from this book is put into practice. In 10 hours, people steps from no Kotlin knowledge to being able to create their own Apps from scratch. Antonio started as a consultant in CRM technologies, but after some time, looking for his real passion, he discovered the Android world. After getting some experience on such an awesome platform, he started a new adventure at a mobile company, where he led several projects for important Spanish companies. He now works as an Android Engineer at Plex2, where he also plays an important role in the design and UX of the Android applications. You can findAntonio on Twitter as@lime_cl3 orGoogle+ as +AntonioLeivaGordillo4. 1http://antonioleiva.com 2http://plex.tv 3https://twitter.com/lime_cl 4http://plus.google.com/+AntonioLeivaGordillo‘
1 Introduction Things are changing for good for Android Developers. The Android team announced during Google I/O 2017 that Kotlin is now an official language to develop Android Apps. This means that, while it’s still possible to develop Android Apps using Java, from now on Kotlin is fully supported and Google will make sure that all new Android features, the framework, the IDE and all their libraries work seamlessly with the new language. Google listened to the community, who was asking for years that Kotlin became a first-party language. So you can now take advantage from all the features of amodern language while developing Android. Throughout this book I’ll show you how, so I hope that I can help you understand the various ways how Kotlin can take you one step ahead and make your code much better. But before diving into the features of the language, let me tell you just a little bit of background. 1.1 What is Kotlin? Kotlin is a JVM based language developed by JetBrains5, a company known for creating IntelliJ IDEA, a powerful IDE for Java development. Android Studio, the official Android IDE, is based on IntelliJ. Kotlin was created with Java developers in mind, and with IntelliJ as its main devel- opment IDE. And these are two very interesting features for Android developers: • 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 in basic concepts can be learnt in no time. 5https://www.jetbrains.com/
1 Introduction 6 • We have total integration with our daily IDE for free. Android Studio can understand, compile and run Kotlin code. And the support for this language comes from the company who develops the IDE, so we Android developers are first-class citizens. But 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’s more expressive: this is one of its most important qualities. You can write more with much less code. • It’s safer: Kotlin is null safe, which means that we deal with possible null situations in compile time, to prevent execution time exceptions. We need to explicitly specify that an object can be null, and then check its nullity before using it. You will save a lot of time debugging null pointer exceptions and fixing nullity bugs. • It’s functional: Kotlin is basically an object oriented language, not a pure functional language. However, as many other modern languages, it uses many concepts from functional programming, such as lambda expressions, to solve some problems in a much easier way. 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 don’t have access to the source code. • It’s highly interoperable: You can continue using most libraries and code written in Java, because the interoperability between both languages is excel- lent. It’s even possible to create mixed projects, with both Kotlin and Java files coexisting. 1.2 What do we get with Kotlin? Without diving too deep into Kotlin language (we’ll learn everything about it throughout this book), these are some interesting features we miss in Java:
1 Introduction 7 Expressiveness With Kotlin, it’s much easier to avoid boilerplate because the most common patterns are covered by default in the language. For instance, in Java, if we want to create a data class, we’ll need to write (or at least generate) this code: 1 public class Artist { 2 private long id; 3 private String name; 4 private String url; 5 private String mbid; 6 7 public long getId() { 8 return id; 9 } 10 11 public void setId(long id) { 12 this.id = id; 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;
1 Introduction 8 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 } With Kotlin, you just need to make use of a data class: 1 data class Artist( 2 var id: Long, 3 var name: String, 4 var url: String, 5 var mbid: String) 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 big amount of our code is defensive. We need to check once and another whether something is null before using it if we don’t want to find unexpected NullPointerException. Kotlin, as 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:
1 Introduction 9 1 // This won't compile. Artist can't be null 2 var notNullArtist: Artist = null 3 4 // Artist can be null 5 var artist: Artist? = null 6 7 // Won't compile, artist could be null and we need to deal with that 8 artist.print() 9 10 // Will print only if artist != null 11 artist?.print() 12 13 // Smart cast. We don't need to use safe call operator if we previously 14 // checked nullity 15 if (artist != null) { 16 artist.print() 17 } 18 19 // Only use it when we are sure it's not null. Will throw an exception otherwise. 20 artist!!.print() 21 22 // Use Elvis operator to give an alternative in case the object is null. 23 val name = artist?.name ?: "empty" Extension functions You can add new functions to any class. It’s a much more readable substitute to the usual utility classes we all have in our projects. You could, for instance, add a new method to fragments to show a toast: 1 fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) { 2 Toast.makeText(getActivity(), message, duration).show() 3 } And then use it like this: 1 fragment.toast("Hello world!")
1 Introduction 10 Functional support (Lambdas) What if, instead of having to declare an anonymous class every time we need to implement a click listener, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambdas: 1 view.setOnClickListener { toast("Hello world!") } This is only a small selection of what Kotlin can do to simplify your code. Now that you know some of the many interesting features of the language, youmay decide this is not for you. If you continue, we’ll start practicing right away in the next chapter.
2 Getting ready Now that you know some little examples of what you may do with Kotlin, I’m sure you want to start to put it into practice as soon as possible. Don’t worry, these first chapters will help you configure your development environment so that you can start writing some code immediately. 2.1 Android Studio First thing you need is to install Android Studio. As you may know, Android Studio is the official Android IDE, which was presented to the public in 2013 as a preview and finally released in 2014. Android Studio is implemented as a plugin over IntelliJ IDEA6, a Java IDE created by Jetbrains7, the company which is also behind Kotlin. So, as you can see, everything is tightly connected. The adoption of Android Studio was an important step forward for Android de- velopers. First, because we left the buggy Eclipse behind and moved to a software specifically designed for Java developers, which gives us a perfect interaction with the language. We enjoy awesome features such as a fast and impressively smart code completion, or really powerful analysing and refactoring tools among others. And second, Gradle8 became the official build system for Android, which meant a whole bunch of new possibilities related to version building and deploy. Two of the most interesting functions are build systems and flavours, which let you create infinite versions of the app (or even different apps) in an easy way while using the same code base. If you are still using Eclipse, I’m afraid you need to switch to Android Studio if you want to follow this book. The Kotlin team is creating a plugin for Eclipse, but it will 6https://www.jetbrains.com/idea 7https://www.jetbrains.com 8https://gradle.org/