Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Mastering Kotlin for Android 14
  • Table Of Contents Toc
  • Feedback & Rating feedback
Mastering Kotlin for Android 14

Mastering Kotlin for Android 14

By : Wangereka
5 (9)
close
close
Mastering Kotlin for Android 14

Mastering Kotlin for Android 14

5 (9)
By: Wangereka

Overview of this book

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.
Table of Contents (22 chapters)
close
close
1
Part 1: Building Your App
6
Part 2: Using Advanced Features
12
Part 3: Code Analysis and Tests
16
Part 4: Publishing Your App

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.

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY