Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Kotlin for Android 14
Mastering Kotlin for Android 14

Mastering Kotlin for Android 14: Build powerful Android apps from scratch using Jetpack libraries and Jetpack Compose

By Harun Wangereka
$31.99 $21.99
Book Apr 2024 370 pages 1st Edition
eBook
$31.99 $21.99
Print
$39.99
Subscription
Free Trial
Renews at $15.99p/m
eBook
$31.99 $21.99
Print
$39.99
Subscription
Free Trial
Renews at $15.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 AI Assistant (beta) to help accelerate your learning
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
Table of content icon View table of contents Preview book icon Preview Book

Mastering Kotlin for Android 14

Get Started with Kotlin Android Development

Kotlin is a static programming language that allows you to write concise and typed code. It’s the language preferred for Android development by Google.

In this chapter, we’ll get to know Kotlin as a programming language. We will cover features that are useful for Android development and their importance for Android developers. Additionally, we’ll cover how to migrate from Java to Kotlin and some useful tips for developers coming from Java backgrounds.

In this chapter, we’re going to cover the following main topics:

  • Introduction to Kotlin
  • Kotlin syntax, types, functions, and classes
  • Migrating from Java to Kotlin
  • Kotlin features for Android developers

Technical requirements

To follow the instructions in this chapter, you’ll need to have the following ready:

You can find the code for this chapter at https://github.com/PacktPublishing/Mastering-Kotlin-for-Android/tree/main/chapterone

Introduction to Kotlin

Kotlin is a language that runs on the Java Virtual Machine (JVM) developed by JetBrains. It was developed to overcome the following challenges that Java had:

  • Verbosity: Java has a very verbose syntax and this leads to developers writing a lot of boilerplate code even for trivial tasks.
  • Null pointer exceptions: By default, Java allows variables to have null values. This normally results in null pointer exceptions, which has been called the billion-dollar mistake in Java as many applications have been affected by this.
  • Concurency: Java has threads, but managing concurrency and thread safety can be such a hard task at times. This leads to a lot of performance and memory issues that seriously affect applications that need to do work off the main thread.
  • Slow adoption of features: The Java release cycle is slow and it is difficult to use the latest Java version to develop Android apps as there’s a lot to be done to ensure backward compatibility. This means it’s hard for Android developers to easily adopt the new language features and improvements as they’re stuck using older versions.
  • Lack of functional support: Java is not a functional language, which makes it hard for developers to write functional code in Java. It’s hard to employ features such as high-order functions or treat functions as first-class citizens.

Over the years, Kotlin has evolved to be multiplatform and server-side and not serviced, and is used in data science as well. Some of the features where Kotlin has an edge over Java are as follows:

  • Conciseness: The syntax is concise, which in turn reduces the amount of boilerplate code that you write.
  • Null safety: Many Java developers are very familiar with the famous Null Pointer Exception that was a source of many bugs and issues in applications. Kotlin was designed with null safety in mind. Variables that can have null values are indicated when declaring them, and before using these variables, the Kotlin compiler enforces checks for nullability, thereby reducing the number of exceptions and crashes.
  • Coroutines support: Kotlin has built-in support for Kotlin coroutines. Coroutines are lightweight threads that you can use to perform asynchronous operations. It’s easy to understand and use them in your applications.
  • Data classes: Kotlin has a built-in data class construct that makes it easy to define classes that are used primarily to store data. Data classes automatically generate equals(), hashCode(), and toString() methods, reducing the amount of boilerplate code required.
  • Extension functions: Kotlin allows developers to add functions to existing classes without inheriting from them, through extension functions. This makes it easier to add functionality to existing classes and reduces the need for boilerplate code.
  • Smart casting: Kotlin’s smart casting system makes it possible to cast variables without the need for an explicit cast. The compiler automatically detects when a variable can be safely cast and performs the cast automatically.

JetBrains is also the company behind IntelliJ IDEA. The language support in this Integrated Development Environment (IDE) is also great.

Kotlin has evolved over the years to support the following different platforms:

  • Kotlin Multiplatform: This is used to develop applications that target different platforms such as Android, iOS, and web applications
  • Kotlin for server side: This is used to write backend applications and a number of frameworks to support server-side development
  • Kotlin for Android: Google has supported Kotlin as a first-class language for Android development since 2017
  • Kotlin for JavaScript: This provides support for writing Kotlin code that is transpiled to compatible JavaScript libraries
  • Kotlin/Native: This compiles Kotlin code to native binaries and runs without a Java Virtual Machine (JVM)
  • Kotlin for data science: You can use Kotlin to build and explore data pipelines

In summary, Kotlin provides a more modern and concise approach to programming than Java while still maintaining interoperability with existing Java libraries and code. In addition, you can write Kotlin code and target different platforms.

Now that we have got the gist of Kotlin and its various features, let’s move on to the next section where we will understand Kotlin as a programming language and understand Kotlin syntax, types, functions, and classes.

Kotlin syntax, types, functions and classes

In this section, we’ll be looking at Kotlin syntax and familiarize ourselves with the language. Kotlin is a strongly typed language. The type of a variable is determined at the time of compilation. Kotlin has a rich type system that has the following types:

  • Nullable types: Every type in Kotlin can either be nullable or non-nullable. Nullable types are denoted with a question mark operator – for example, String?. Non-nullable types are normal types without any operator at the end – for example, String.
  • Basic types: These types are similar to Java. Examples include Int, Long, Boolean, Double, and Char.
  • Class types: As Kotlin is an object-oriented programming language, it provides support for classes, sealed classes, interfaces, and so on. You define a class using the class keyword and you can add methods, properties, and constructors.
  • Arrays: There is support for both primitive and object arrays. To declare a primitive array, you specify the type and size, as follows:
    val shortArray = ShortArray(10)

    The following shows how you define object arrays:

    val recipes = arrayOf("Chicken Soup", "Beef Stew", "Tuna Casserole")

    Kotlin automatically infers the type when you don’t specify it.

  • Collections: Kotlin has a rich collection of APIs providing types such as sets, maps, and lists. They’re designed to be concise and expressive, and the language offers a wide range of operations for sorting, filtering, mapping, and many more.
  • Enum types: These are used to define a fixed set of options. Kotlin has the Enum keyword for you to declare enumerations.
  • Functional types: Kotlin is a functional language as well, meaning functions are treated as first-class citizens. You can be able to assign functions to variables, return functions as values from functions, and pass functions as arguments to other functions. To define a function as a type, you use the (Boolean) -> Unit shorthand notation. This example takes a Boolean argument and returns a Unit value.

We’ve learned the different types available in Kotlin, and we’ll use this knowledge in the next section to define some of these types.

Creating a Kotlin project

Follow these steps to create your first Kotlin project:

  1. Open IntelliJ IDEA. On the welcome screen, click on New Project. You’ll be presented with a dialog to create your new project as shown in the following figure:
Figure 1.1 – New Project dialog

Figure 1.1 – New Project dialog

Let’s work through the options in the dialog shown in Figure 1.1 as follows:

  1. You start by giving the project a name. In this case, it’s chapterone.
  2. You also specify the location of your project. This is normally where you store your working projects. Change the directory to your preferred one.
  3. Next, specify your target language from the options provided. In this case, we opt for Kotlin.
  4. In the next step, specify your build system. We specify Gradle.
  5. We also need to specify the Java version that our project is going to use. In this case, it’s Java 11.
  6. Next, you specify the Gradle DSL to use. For this project, we’ve chosen to use Kotlin.
  7. Lastly, you specify the group and artifact IDs that, when combined, form a unique identifier for your project.
  1. Click on Create to finalize creating your new project. The IDE will create your project, which might take a few minutes. Once done, you’ll see your project as follows:

Figure 1.2 – Project structure

Figure 1.2 – Project structure

The IDE creates the project with the project structure seen in Figure 1.2. We are mostly interested in the src/main/kotlin package, which is where we’ll add our Kotlin files.

  1. Start by right-clicking the src/main/kotlin package.
  2. Select New and then New Kotlin Class/File. Select the File option from the list that appears and name the file Main. The IDE will generate a Main.kt file.

Now that we’ve created our first Kotlin project and added a Kotlin file, in the next section, we will create functions in this file.

Creating functions

In Kotlin, a function is a block of code that does a specific task. We use the fun keyword to define functions. Function names should be in camel case and descriptive to indicate what the function is doing. Functions can take arguments and return values.

Create the main() function in your Main.kt file as follows:

fun main() {
    println("Hello World!")
}

In the preceding code, we’ve used the fun keyword to define a function with the name main. Inside the function, we have a println statement that prints the message "Hello Word!".

You can run the function by pressing the green run icon to the right of the function. You’ll see the console window pop up, displaying the message "Hello World!".

We’ve learned how to create functions and print output to the console. In the next section, we’ll learn how to create classes in Kotlin.

Creating classes

To declare a class in Kotlin, we have the class keyword. We’re going to create a Recipe class as follows:

class Recipe {
    private val ingredients = mutableListOf<String>()
    fun addIngredient(name: String) {
        ingredients.add(name)
    }
    fun getIngredients(): List<String> {
        return ingredients
    }
}

Let’s break down the preceding class:

  • We’ve called the class Recipe and it has no constructor.
  • Inside the class, we have a member variable, ingredients, which is a MutableList of Strings. It’s mutable to allow us to add more items to the list. Defining variables in a class like this allows us to be able to access the variable anywhere in the class.
  • We have addIngredient(name: String), which takes in a name as an argument. Inside the function, we add the argument to our ingredients list.
  • Lastly, we have the getIngredients() function, which returns an immutable list of strings. It simply returns the value of our ingredients list.

To be able to use the class, we have to modify our main function as follows:

fun main() {
    val recipe = Recipe()
    recipe.addIngredient("Rice")
    recipe.addIngredient("Chicken")
    println(recipe.getIngredients())
}

The changes can be explained as follows:

  • First, we create a new instance of the Recipe class and assign it to the recipe variable
  • Then, we call the addIngredient method on the recipe variable and pass in the string Rice
  • Again, we call the addIngredient method on the recipe variable and pass in the string Chicken
  • Lastly, we call the getIngredients method on the recipe variable and print the result to the console

Run the main function again and your output should be as follows:

Figure 1.3 – Recipes

Figure 1.3 – Recipes

As you can see from the preceding screenshot, the output is a list of ingredients that you added! Now you can prepare a nice rice and chicken meal, but in Kotlin!

Kotlin has tons of features and we’ve barely scratched the surface. You can check out the official Kotlin documentation (https://kotlinlang.org/docs/home.html) as well to learn more. You’ll also learn more features as you go deeper into this book.

We’ve learned how to create classes, define top-level variables, and add functions to our class. This helps us understand how classes in Kotlin work. In the next section, we will learn how to migrate a Java class to Kotlin and some of the tools available to use in the migration.

Migrating from Java to Kotlin

Are you a Java developer and have your apps in Java? Are you wondering how you could get started with Kotlin? Worry not, this is your section. Kotlin offers two ways for you:

  • Java-to-Kotlin migration: The IDE that we are using, IntelliJ IDEA, has a tool for converting existing Java files to Kotlin.
  • Interoperability: Kotlin is highly interoperable with Java code, meaning you can have both Java and Kotlin code in the same project. You can continue using your favorite Java libraries in your Kotlin projects.

Let’s see how to migrate a sample Java class to Kotlin using IntelliJ IDEA:

  1. Inside src/main/kotlin, open the Song class, which has a number of Java functions.
  2. Right-click the file and you’ll see the Convert Java to Kotlin option at the bottom. Select this and you’ll be presented the following confirmation dialog:

Figure 1.4 – Confirmation dialog

Figure 1.4 – Confirmation dialog

At times after a conversion, you might need to make some corrections and that’s why we have this dialog. Click Yes to proceed and you’ll see your code is now in Kotlin. This is a useful feature that handles a major part of the conversion to Kotlin and you also learn about the syntax.

Now that we’ve learned how to migrate Java code to Kotlin, in the next section we will cover some of the features of Kotlin that make it useful for Android developers.

Kotlin features for Android developers

Now that you have had an introduction to Kotlin, let’s look at why Kotlin is a great language specifically for Android development.

Google announced Kotlin as a first-class language for writing Android apps back in 2017. Since then, there has been lots of work done to make sure that developers have all they need to develop Android apps in Kotlin. Here are some of the features that developers can benefit from:

  • Improved developer productivity: Kotlin’s concise and expressive syntax can help developers write code faster and with fewer errors, which can ultimately improve developer productivity.
  • Null safety: Since Kotlin is written with nullability in mind, it helps us to avoid crashes related to the Null Pointer Exception.
  • IDE support: IDE support has been continuously improving. Android Studio, which is built on top of IntelliJ IDEA, has been receiving tons of features such as improved autocompletion support to improve the Kotlin experience.
  • Jetpack libraries: Jetpack libraries are available in Kotlin, and older ones are being rewritten with Kotlin. These are a set of libraries and tools to help Android developers write less code. They address common developer pain points and increase developer efficiency.
  • Jetpack Compose: Jetpack Compose, a new UI framework, is completely written in Kotlin and takes advantage of features of the Kotlin language. It’s a declarative UI framework that makes it easy for Android developers to build beautiful UIs for their apps.
  • Kotlin Gradle DSL: You are now able to write your Gradle files in Kotlin.
  • Coroutine support: A lot of Jetpack Libraries support coroutines. For example, the ViewModel class has viewModelScope that you can use to scope coroutines in the lifecycle of the ViewModel. This aligns with the Structured Concurrency principles for coroutines. This helps cancel all coroutines when they’re no longer needed. Some libraries including Room, Paging 3, and DataStore also support Kotlin coroutines.
  • Support from Google: Google continues to invest in Kotlin. Currently, there are resources ranging from articles to code labs, documentation, videos, and tutorials from the Android DevRel team at Google to assist you in learning new libraries and architecture for Android Development.
  • Active community and tooling: Kotlin has a vibrant and active community of developers, which means that there are plenty of unofficial resources, libraries, and tools available to help with Android development.

Summary

In this chapter, we learned about the Kotlin programming language and its features. We explored the Kotlin features that are useful for Android development and why it’s important to Android developers. Additionally, we covered how to migrate from Java to Kotlin and some useful tips for developers coming from Java backgrounds.

In the next chapter, we’ll learn how to create Android apps with Android Studio. We will explore some of the features that Android Studio offers and learn some tips and shortcuts.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Apply best practices and industry-essential skills used by Google Developer Experts
  • Find out how to publish, monitor, and improve your app metrics on the Google Play Store
  • Learn how to debug issues, detect leaks, inspect network calls, and inspect your app’s local database
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Written with the best practices, this book will help you master Kotlin and use its powerful language features, libraries, tools, and APIs to elevate your Android apps. As you progress, you'll use Jetpack Compose and Material Design 3 to build UIs for your app, explore how to architect and improve your app architecture, and use Jetpack Libraries like Room and DataStore to persist your data locally. Using a step-by-step approach, this book will teach you how to debug issues in your app, detect leaks, inspect network calls fired by your app, and inspect your Room database. You'll also add tests to your apps to detect and address code smells. Toward the end, you’ll learn how to publish apps to the Google Play Store and see how to automate the process of deploying consecutive releases using GitHub actions, as well as learn how to distribute test builds to Firebase App Distribution. Additionally, the book covers tips on how to increase user engagement. By the end of this Kotlin book, you’ll be able to develop market-ready apps, add tests to their codebase, address issues, and get them in front of the right audience.

What you will learn

Build beautiful, responsive, and accessible UIs with Jetpack Compose Explore various app architectures and find out how you can improve them Perform code analysis and add unit and instrumentation tests to your apps Publish, monitor, and improve your apps in the Google Play Store Perform long-running operations with WorkManager and persist data in your app Use CI/CD with GitHub Actions and distribute test builds with Firebase App Distribution Find out how to add linting and static checks on CI/CD pipelines

Product Details

Country selected

Publication date : Apr 5, 2024
Length 370 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837631711
Vendor :
JetBrains
Category :

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 AI Assistant (beta) to help accelerate your learning
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

Product Details


Publication date : Apr 5, 2024
Length 370 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837631711
Vendor :
JetBrains
Category :

Table of Contents

22 Chapters
Preface Chevron down icon Chevron up icon
1. Part 1: Building Your App Chevron down icon Chevron up icon
2. Chapter 1: Get Started with Kotlin Android Development Chevron down icon Chevron up icon
3. Chapter 2: Creating Your First Android App Chevron down icon Chevron up icon
4. Chapter 3: Jetpack Compose Layout Basics Chevron down icon Chevron up icon
5. Chapter 4: Design with Material Design 3 Chevron down icon Chevron up icon
6. Part 2: Using Advanced Features Chevron down icon Chevron up icon
7. Chapter 5: Architect Your App Chevron down icon Chevron up icon
8. Chapter 6: Network Calls with Kotlin Coroutines Chevron down icon Chevron up icon
9. Chapter 7: Navigating within Your App Chevron down icon Chevron up icon
10. Chapter 8: Persisting Data Locally and Doing Background Work Chevron down icon Chevron up icon
11. Chapter 9: Runtime Permissions Chevron down icon Chevron up icon
12. Part 3: Code Analysis and Tests Chevron down icon Chevron up icon
13. Chapter 10: Debugging Your App Chevron down icon Chevron up icon
14. Chapter 11: Enhancing Code Quality Chevron down icon Chevron up icon
15. Chapter 12: Testing Your App Chevron down icon Chevron up icon
16. Part 4: Publishing Your App Chevron down icon Chevron up icon
17. Chapter 13: Publishing Your App Chevron down icon Chevron up icon
18. Chapter 14: Continuous Integration and Continuous Deployment Chevron down icon Chevron up icon
19. Chapter 15: Improving Your App Chevron down icon Chevron up icon
20. Index Chevron down icon Chevron up icon
21. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
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.