Peter Späth
Learn Kotlin for Android DevelopmentThe Next Generation Language for Modern Android Apps Programming
Peter Späth
Leipzig, Germany
ISBN 978-1-4842-4466-1e-ISBN 978-1-4842-4467-8
© Peter Späth 2019
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

To Alina

Introduction

Computer programs are for executing operations using input data to produce output data, sometimes by manipulating data taken from a database during that operation. The word database here is used in the most general sense: It could be a file, some memory storage, or a full-fledged database product.

Many different programming languages exist nowadays, each with its own merits and drawbacks. Some of them aim at execution stability, some at high performance, some are tailored to solve specific tasks, and some exist only because a company wants to establish a strong market position. Looking at the way programming languages have developed over time is an interesting subject in and of itself, and it has implications for various aspects of information technology. One could write a separate book about that, but for this book I simply want to stress one important fact about computer language development, which I think has a direct effect on the way modern computer programs are written. If you are looking at the historical development of computer languages, you will notice a substantial change in the abstraction level the languages exhibit. Whereas in the infancy of the industry a programmer needed to have a fairly good knowledge of computer hardware, now different levels of abstraction have been introduced into the languages, meaning an increased conceptional and linguistic distance from hardware features. This has increasingly alleviated the requirement that software developers know what is occurring in a computer’s central processing unit (CPU).

Along with an increasing level of abstraction, modern computer languages—sometimes implicitly, sometimes explicitly—exhibit a prominent new feature: the expressiveness of language constructs. Let me try to illustrate this using an example written in pseudo-code. Let’s say you have a list of items and want to perform an operation on each of the items. With some knowledge of the internal functioning of computers, a programmer might write a code snippet like this:
  • Create some array of data in the memory.

  • Assign a pointer to the first element.

  • Loop over the array.
    • Dereference the pointer, retrieving a list element.

    • Do something with the element (example.g., print it).

    • Increment the pointer, let it point to the next item.

    • If we are beyond the last element, exit the loop.

  • End loop.

Although this looks a little bit complex, it closely relates to what computers are doing under the hood, and early languages looked more or less like this. As a first abstraction and a way to improve readability, we can try to get rid of the “pointer” element and instead write:
  • variable theList = [somehow create the list of items]
    • loop over "theList", assigning each item to an iteration variable "item":

    • do something with "item", for example print it

  • end loop

This already looks more expressive compared to the first version, and a lot of current programming languages allow for this kind of programming style. We can do even better, though: You can see the definition of the list being written in one line, separated from the list processing in the loop. There’s nothing preventing us from writing a lot of overly complex code between the list definition and the loop, and this is what you see quite often, making the program hard to read and understand. Wouldn’t it be better to have it all in one statement? Using a more expressive snippet allows us to write such a combined statement. In pseudo-code, it could look like this:

[somehow create the list of items].
    [maybe add some filter].
    forEach { item ->
      do something with "item", for example print it
    }

This is about the maximum of expressiveness you can get, if you see the dot “ . ” as some kind of “do something with it” command and “{ … }” as a block of code doing something, with the identifier in front of the -> in this case designating a loop variable.

Note

Making your code expressive from the very beginning will not only help you to write good code, it will also help you to develop your programming skills beyond average. Expressive code is easier to maintain and extend, easier to reuse, easier to understand for others, and easier to debug if the program shows some deficiencies.

The programming language Kotlin is capable of getting us to such an extent of expressiveness, and in this book I want to introduce Kotlin as a programming language for Android that allows you to accomplish things in an expressive and concise way. As a matter of fact, in Kotlin the little looping example, with a filter added, reads:

arrayOf("Blue", "Green", "Yellow", "Gray").
    filter { it.startsWith("G") }.
    forEach { item ->
      println(item)
    }

If you run this, it will print the text Green Gray on two lines of the console. With the notion of parameters being placed inside round brackets, you should be able to understand this snippet without knowing a single Kotlin idiom.

Note

Don’t worry if you don’t know how to write and run this, we’ll be getting our feet wet very soon in the first chapter of the book.

Once you reach the end of the book, you should be an advanced developer able to address problems in the Kotlin language, with particular attention on Android matters. Of course, you will not know all possible libraries that are out there in the wild for solving specific problems, as only experience will help you there. Knowing most of the language constructs and having good ideas concerning programming techniques, however, will set you on the way to become an expert programmer for Android.

The Kotlin version referred to in this book is 1.3. Most of the examples and most of what gets explained here is likely valid for later versions as well.

The Book’s Target Audience

The book is for beginning software developers with little or no knowledge of programming, and for developers with knowledge of other languages who are interested in using Kotlin for future Android projects. The target platforms are Android devices. The book is not meant to present a thorough introduction into Android; instead, it uses Android as a platform as is and thoroughly introduces the Kotlin programming language and how it gets used for Android.

Basic knowledge of how to use a desktop or laptop computer, including the installation and starting of programs, is expected. The operating system you want to use plays no major role, but because we are using Android Studio as a development environment, you must choose an operating system able to run this integrated development environment (IDE). This is the case for Linux, Windows, and Mac OS. Screenshots are taken from an Ubuntu Linux installation.

In the end, you will be able to write and run Kotlin programs for Android of beginning to midlevel complexity.

Source Code

All source code shown or referred to in this book can be found at

https://github.com/Apress/learn-kotlin-for-android-development

How to Read This Book

Reading this book sequentially from the beginning to the end will provide the maximum benefit. If you already have some basic development knowledge, you can skip sections and chapters at will, and of course you can always take a step back and reread sections and chapters while you are advancing through the book.

Table of Contents

Index 501

About the Author and About the Technical Reviewer

About the Author

Peter Späth

graduated in 2002 as a physicist and soon afterward became an IT consultant, mainly for Java-related projects. In 2016 he decided to concentrate on writing books on various subjects, with a primary focus on software development. With a wealth of experience in Java-related languages, the release of Kotlin for building Android apps made him enthusiastic about writing books for Kotlin development in the Android environment.

 

About the Technical Reviewer

Ted Hagos

is the CTO and Data Protection Officer of RenditionDigital International (RDI), a software development company based out of Dublin. Before he joined RDI, he had various software development roles and also spent time as a trainer at IBM Advanced Career Education, Ateneo ITI, and Asia Pacific College. He spent many years in software development, dating back to the days of Turbo C, Clipper, dBase IV, and Visual Basic. Eventually, he found Java and spent many years working on Java-related projects. Nowadays, he’s busy with full-stack JavaScript and Android.

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.104.248