Search icon
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
€14.99 per month
Book Apr 2024 370 pages 1st Edition
eBook
€26.99 €17.99
Print
€33.99
Subscription
€14.99 Monthly
eBook
€26.99 €17.99
Print
€33.99
Subscription
€14.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.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 : Apr 5, 2024
Length 370 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781837631711
Vendor :
JetBrains
Category :
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

What do you get with a Packt Subscription?

Free for first 7 days. $15.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 : 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
Part 1: Building Your App Chevron down icon Chevron up icon
Chapter 1: Get Started with Kotlin Android Development Chevron down icon Chevron up icon
Chapter 2: Creating Your First Android App Chevron down icon Chevron up icon
Chapter 3: Jetpack Compose Layout Basics Chevron down icon Chevron up icon
Chapter 4: Design with Material Design 3 Chevron down icon Chevron up icon
Part 2: Using Advanced Features Chevron down icon Chevron up icon
Chapter 5: Architect Your App Chevron down icon Chevron up icon
Chapter 6: Network Calls with Kotlin Coroutines Chevron down icon Chevron up icon
Chapter 7: Navigating within Your App Chevron down icon Chevron up icon
Chapter 8: Persisting Data Locally and Doing Background Work Chevron down icon Chevron up icon
Chapter 9: Runtime Permissions Chevron down icon Chevron up icon
Part 3: Code Analysis and Tests Chevron down icon Chevron up icon
Chapter 10: Debugging Your App Chevron down icon Chevron up icon
Chapter 11: Enhancing Code Quality Chevron down icon Chevron up icon
Chapter 12: Testing Your App Chevron down icon Chevron up icon
Part 4: Publishing Your App Chevron down icon Chevron up icon
Chapter 13: Publishing Your App Chevron down icon Chevron up icon
Chapter 14: Continuous Integration and Continuous Deployment Chevron down icon Chevron up icon
Chapter 15: Improving Your App Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
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%

Filter reviews by


No reviews found
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.