Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Android Development with Kotlin
Android Development with Kotlin

Android Development with Kotlin: Enhance your skills for Android development using Kotlin

Arrow left icon
Profile Icon Marcin Moskala Profile Icon Igor Wojda
Arrow right icon
€8.99 €29.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.6 (5 Ratings)
eBook Aug 2017 440 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Marcin Moskala Profile Icon Igor Wojda
Arrow right icon
€8.99 €29.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.6 (5 Ratings)
eBook Aug 2017 440 pages 1st Edition
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Android Development with Kotlin

Laying a Foundation

This chapter is largely devoted to the fundamental building blocks that are core elements of the Kotlin programming language. Each one may seem insignificant by itself, but combined together, they create really powerful language constructs. We will discuss the Kotlin type system that introduces strict null safety and smart casts. Also, we will see a few new operators in the JVM world, and many improvements compared to Java. We will also present new ways to handle application flows and deal with equality in a unified way.

In this chapter, we will cover the following topics:

  • Variables, values, and constants
  • Type inference
  • Strict null safety
  • Smart casts
  • Kotlin data types
  • Control structures
  • Exceptions handling

Variables

In Kotlin, we have two types of variables: var and val. The first one, var, is a mutable reference (read-write) that can be updated after initialization. The var keyword is used to define a variable in Kotlin. It is equivalent to a normal (non-final) Java variable. If our variable needs to change at some point, we should declare it using the var keyword. Let's look at an example of a variable declaration:

    fun main(args: Array<String>) { 
        var fruit: String =  "orange" //1 
        fruit  = "banana" //2 
    } 
  1. Create a fruit variable and initialize it with the vale of the orange variable.
  2. Reinitialize the fruit variable with the value of the banana variable.

The second type of variable is a read-only reference. This type of variable cannot be reassigned after initialization.

The val keyword can contain...

Type inference

As we saw in previous examples, unlike Java, the Kotlin type is defined after the variable name:

    var title: String 

At first glance, this may look strange to Java developers, but this construct is a building block of a very important feature of Kotlin called type inference. Type inference means that the compiler can infer type from context (the value of an expression assigned to a variable). When variable declaration and initialization is performed together (single line), we can omit the type declaration. Let's look at the following variable definition:

    var title: String = "Kotlin" 

The type of the title variable is String, but do we really need an implicit type declaration to determine variable type? On the right side of the expression, we have a string, Kotlin and we are assigning it to a variable, title, defined on the left...

Strict null safety

According to Agile Software Assessment (http://p3.snf.ch/Project-144126) research, a missing null check is the most frequent pattern of bugs in Java systems. The biggest source of errors in Java is NullPointerExceptions. It's so big that speaking at a conference in 2009, Sir Tony Hoare apologized for inventing the null reference, calling it a billion-dollar mistake (https://en.wikipedia.org/wiki/Tony_Hoare).

To avoid NullPointerException, we need to write defensive code that checks if an object is null before using it. Many modern programming languages, including Kotlin, made steps to convert runtime errors into compile time errors to improve programming language safety. One of the ways to do it in Kotlin is by adding nullability safeness mechanisms to language type systems. This is possible because the Kotlin type system distinguishes between references...

Nullability and Java

We know that Kotlin requires us to explicitly define references that can hold null values. Java on the other hand is much more lenient about nullability, so we may wonder how Kotlin handles types coming from Java (basically the whole Android SDK and libraries written in Java). Whenever possible, the Kotlin compiler will determine type nullability from the code and represent types as actual nullable or non-nullable types using nullability annotations.

The Kotlin compiler supports several flavors of nullability annotations, including:
  • Android (com.android.annotations and android.support.annotations)
  • JetBrains (@Nullable and @NotNull from the org.jetbrains.annotations package)
  • JSR-305 (Javax.annotation)
We can find the full list in the Kotlin compiler source code (https://github.com/JetBrains/kotlin/blob/master/core/descriptor.loader.Java/src/org/jetbrains...

Casts

The casting concept is supported by many programming languages. Basically, casting is a way to convert an object of one particular type into another type. In Java, we need to cast an object explicitly before accessing its member, or cast it and store it in the variable of the casted type. Kotlin simplifies concept of casting and moves it to the next level by introducing smart casts.

In Kotlin, we can perform a few types of cast:

  • Cast objects to different types explicitly (safe cast operator)
  • Cast objects to different types, or nullable types to non-nullable types, implicitly (smart cast mechanism)

Safe/unsafe cast operator

In strongly typed languages, such as Java or Kotlin, we need to convert values from one type...

Variables


In Kotlin, we have two types of variables: var and val. The first one, var, is a mutable reference (read-write) that can be updated after initialization. The var keyword is used to define a variable in Kotlin. It is equivalent to a normal (non-final) Java variable. If our variable needs to change at some point, we should declare it using the var keyword. Let's look at an example of a variable declaration:

    fun main(args: Array<String>) { 
        var fruit: String =  "orange" //1 
        fruit  = "banana" //2 
    } 
  1. Create a fruit variable and initialize it with the vale of the orange variable.
  2. Reinitialize the fruit variable with the value of the banana variable.

The second type of variable is a read-only reference. This type of variable cannot be reassigned after initialization.

Note

The val keyword can contain a custom getter, so technically it can return different objects on each access. In other words, we can't guarantee that the reference to the underlying object is...

Type inference


As we saw in previous examples, unlike Java, the Kotlin type is defined after the variable name:

    var title: String 

At first glance, this may look strange to Java developers, but this construct is a building block of a very important feature of Kotlin called type inference. Type inference means that the compiler can infer type from context (the value of an expression assigned to a variable). When variable declaration and initialization is performed together (single line), we can omit the type declaration. Let's look at the following variable definition:

    var title: String = "Kotlin" 

The type of the title variable is String, but do we really need an implicit type declaration to determine variable type? On the right side of the expression, we have a string, Kotlin and we are assigning it to a variable, title, defined on the left-hand side of the expression.

We specified a variable type as String, but it was obvious, because this is the same type as the type of assigned expression...

Strict null safety


According to Agile Software Assessment(http://p3.snf.ch/Project-144126) research, a missing null check is the most frequent pattern of bugs in Java systems. The biggest source of errors in Java is NullPointerExceptions. It's so big that speaking at a conference in 2009, Sir Tony Hoare apologized for inventing the null reference, calling it a billion-dollar mistake (https://en.wikipedia.org/wiki/Tony_Hoare).

To avoid NullPointerException, we need to write defensive code that checks if an object is null before using it. Many modern programming languages, including Kotlin, made steps to convert runtime errors into compile time errors to improve programming language safety. One of the ways to do it in Kotlin is by adding nullability safeness mechanisms to language type systems. This is possible because the Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-nullable references). This single feature of Kotlin...

Nullability and Java


We know that Kotlin requires us to explicitly define references that can hold null values. Java on the other hand is much more lenient about nullability, so we may wonder how Kotlin handles types coming from Java (basically the whole Android SDK and libraries written in Java). Whenever possible, the Kotlin compiler will determine type nullability from the code and represent types as actual nullable or non-nullable types using nullability annotations.

Note

The Kotlin compiler supports several flavors of nullability annotations, including:

  • Android (com.android.annotations and android.support.annotations)
  • JetBrains (@Nullable and @NotNull from the org.jetbrains.annotations package)
  • JSR-305 (Javax.annotation)

We can find the full list in the Kotlin compiler source code (https://github.com/JetBrains/kotlin/blob/master/core/descriptor.loader.Java/src/org/jetbrains/kotlin/load/Java/JvmAnnotationNames.kt).

We have seen this previously in Activity's onCreate method, where the savedInstanceState...

Casts


The casting concept is supported by many programming languages. Basically, casting is a way to convert an object of one particular type into another type. In Java, we need to cast an object explicitly before accessing its member, or cast it and store it in the variable of the casted type. Kotlin simplifies concept of casting and moves it to the next level by introducing smart casts.

In Kotlin, we can perform a few types of cast:

  • Cast objects to different types explicitly (safe cast operator)
  • Cast objects to different types, or nullable types to non-nullable types, implicitly (smart cast mechanism)

Safe/unsafe cast operator

In strongly typed languages, such as Java or Kotlin, we need to convert values from one type to another explicitly using the cast operator. A typical casting operation is taking an object of one particular type and turning it into another object type that is its supertype (upcasting), subtype (downcasting), or interface. Let's start with a small reminder of casting that...

Primitive data types


In Kotlin, everything is an object (reference type, not primitive type). We don't find primitive types, like the ones we can use in Java. This reduces code complexity. We can call methods and properties on any variable. For example, this is how we can convert the Int variable to a Char:

    var code: Int = 75 
    code.toChar() 

Usually (whenever it is possible), under the hood types such as Int, Long, or Char are optimized (stored as primitive types) but we can still call methods on them as on any other objects.

By default, the Java platform stores numbers as JVM primitive types, but when a nullable number reference (for example, Int?), is needed or generics are involved, Java uses boxed representation. Boxing means wrapping a primitive type into a corresponding boxed primitive type. This means that the instance behaves as an object. Examples of Java boxed representations of primitive types are int versus Integer or a long versus Long Since Kotlin is compiled to JVM bytecode...

Composite data types


Let's discuss more complex types built into Kotlin. Some data types have major improvements compared to Java, while others are totally new.

Strings

Strings in Kotlin behave in a similar way as in Java, but they have a few nice improvements.

To start to access characters at a specified index, we can use the indexing operator and access characters the same way we access array elements:

    val str = "abcd" 
    println (str[1]) // Prints: b 

We also have access to various extensions defined in the Kotlin standard library, which make working with strings easier:

    val str = "abcd" 
    println(str.reversed()) // Prints: dcba 
    println(str.takeLast(2)) // Prints: cd 
    println("john@test.com".substringBefore("@")) // Prints: john 
    println("john@test.com".startsWith("@")) // Prints: false 

This is exactly the same String class as in Java, so these methods are not part of String class. They were defined as extensions. We will learn more about extensions in Chapter 7, Extension...

Statements versus expressions


Kotlin utilizes expressions more widely than Java, so it is important to know the difference between a statement and an expression. A program is basically a sequence of statements and expressions. An expression produces a value, which can be used as part of another expression, variable assignment, or function parameter. An expression is a sequence of one or more operands (data that is manipulated) and zero or more operators (a token that represents a specific operation) that can be evaluated to a single value:

Let's review some examples of expressions from Kotlin:

Expression (produces a value)

Assigned value

Expression of type

a = true

true

Boolean

a = "foo" + "bar"

"foobar"

String

a = min(2, 3)

2

Integer

a = computePosition().getX()

Value returned by the getX method

Integer

 

Statements, on the other hand, perform an action and cannot be assigned to a variable, because they simply don't have a value. Statements can contain language keywords that are used to define classes (class...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Leverage specific features of Kotlin to ease Android application development
  • • Write code based on both object oriented and functional programming to build robust applications
  • • Filled with various practical examples so you can easily apply your knowledge to real world scenarios
  • • Identify the improved way of dealing with common Java patterns

Description

Nowadays, improved application development does not just mean building better performing applications. It has become crucial to find improved ways of writing code. Kotlin is a language that helps developers build amazing Android applications easily and effectively. This book discusses Kotlin features in context of Android development. It demonstrates how common examples that are typical for Android development, can be simplified using Kotlin. It also shows all the benefits, improvements and new possibilities provided by this language. The book is divided in three modules that show the power of Kotlin and teach you how to use it properly. Each module present features in different levels of advancement. The first module covers Kotlin basics. This module will lay a firm foundation for the rest of the chapters so you are able to read and understand most of the Kotlin code. The next module dives deeper into the building blocks of Kotlin, such as functions, classes, and function types. You will learn how Kotlin brings many improvements to the table by improving common Java concepts and decreasing code verbosity. The last module presents features that are not present in Java. You will learn how certain tasks can be achieved in simpler ways thanks to Kotlin. Through the book, you will learn how to use Kotlin for Android development. You will get to know and understand most important Kotlin features, and how they can be used. You will be ready to start your own adventure with Android development with Kotlin.

Who is this book for?

This book is for developers who have a basic understanding of Java language and have 6-12 months of experience with Android development and developers who feel comfortable with OOP concepts.

What you will learn

  • ? Run a Kotlin application and understand the integration with Android Studio
  • ? Incorporate Kotlin into new/existing Android Java based project
  • ? Learn about Kotlin type system to deal with null safety and immutability
  • ? Define various types of classes and deal with properties
  • ? Define collections and transform them in functional way
  • ? Define extensions, new behaviours to existing libraries and Android framework classes
  • ? Use generic type variance modifiers to define subtyping relationship between generic types
  • ? Build a sample application

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 30, 2017
Length: 440 pages
Edition : 1st
Language : English
ISBN-13 : 9781787128989
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 30, 2017
Length: 440 pages
Edition : 1st
Language : English
ISBN-13 : 9781787128989
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
Programming Kotlin
€36.99
Mastering Android Development with Kotlin
€36.99
Android Development with Kotlin
€36.99
Total 110.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Beginning Your Kotlin Adventure Chevron down icon Chevron up icon
Laying a Foundation Chevron down icon Chevron up icon
Playing with Functions Chevron down icon Chevron up icon
Classes and Objects Chevron down icon Chevron up icon
Functions as First-Class Citizens Chevron down icon Chevron up icon
Generics Are Your Friends Chevron down icon Chevron up icon
Extension Functions and Properties Chevron down icon Chevron up icon
Delegates Chevron down icon Chevron up icon
Making Your Marvel Gallery Application Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.6
(5 Ratings)
5 star 20%
4 star 0%
3 star 20%
2 star 40%
1 star 20%
Mikolaj Leszczynski Sep 21, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book. This is for Android developers who would like to learn how to apply Kotlin paradigms to typical Android development patterns. Makes for a very practical approach to teaching Kotlin.
Amazon Verified review Amazon
Amazon Customer Oct 07, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Good explanation of Kotlin and advantages over Java. I expected more Android references given the book title so that aspect is a little underwhelming since I am primarily concerned with learning Kotlin for Android development. Though, the last chapter is dedicated to building a gallery app (which I've yet to reach).English is not great, and the grammatical errors don't help, but it is still readable overall. Definitely seems like a number of the issues should have been caught prior to publishing.Overall, so far, I am pleased with the content. My rating may change from a 3 star once I finish reading the entire book.
Amazon Verified review Amazon
Bob Mann Sep 30, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I have made it halfway through this book and only because I worked through a much better book before I read this one.Android Studio Development Essentials by Neil Smyth is an example of a GOOD Android Studio Tutorial.Android Development with Kotlin by Marcin Moskala is an example of a BAD Android Studio Tutorial.When I see a code example " println(Text) " I know the author is not using Android Studio.When I see Github listing just code snippets instead of working examples I know the author is not using Android Studio.When I see Github code organized in Chapters and no Chapter numbers in the downloaded book I know the editor did not read all of the content.I can work around the broken english in this book and I really want to learn Kotlin on Android Studio, I guess the only way I will is when Neil Smyth writes a Kotlin version of his Android Studio Development Essentials.
Amazon Verified review Amazon
Ollie C Sep 25, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
The breadth of coverage and touching on Android are valuable and the authors clearly have a great deal of knowledge about Kotlin but the book is severely let down by typos, poor grammar, code sample errors (one defines a class called Snail but instantiates one called Sneil!), duplicated text, images that are unreadable on a Kindle and poor English which is distracting (it's instead of its, sentences missing definite/indefinite articles, missing words, capital letters in the middle of sentences, etc). It's not an exaggeration to say most pages have errors on them, making it incredibly difficult to read and very poor value for money. Even one of the book's chapter *titles* has a glaring typo in it ("View binging" instead of "View binding"!). It's clear this book was not even looked at by a technical book editor. Packt told me they are now editing the book, but why didn't they do this before publishing it? Come on! Although the book does contain some Android examples there are very few. Kotlin in Action is a significantly higher quality book, in which I saw not a single copy error. It also contains Android examples and so I heartily recommend that as an alternative.
Amazon Verified review Amazon
Xolix Sep 14, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This is probably the worst book for anyone starting out with Android development and Kotlin. The book is essentially a long list of loosely related details that might come up when working in Kotlin. Maybe there could have been a place for it as reference, but then of course it is already outdated. The one and only project - if one wants to call it that - starts on page 338 and assumes that one has read through the encyclopedic style of some hundred mini-topics. At that pint one then gets to type in reams of xml as the books doesn’t get into layout or other Android Studio related issues and any explanations from this point on are extremely brief or non-existing. Just thoughtless and horrible.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.