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
€18.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.6 (5 Ratings)
Paperback 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
€18.99 per month
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.6 (5 Ratings)
Paperback 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 a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781787123687
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 30, 2017
Length: 440 pages
Edition : 1st
Language : English
ISBN-13 : 9781787123687
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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.