Reader small image

You're reading from  Mastering Kotlin for Android 14

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781837631711
Edition1st Edition
Languages
Right arrow
Author (1)
Harun Wangereka
Harun Wangereka
author image
Harun Wangereka

Harun Wangereka is a Google Developer Expert for Android and an Android engineer with over seven years of experience and currently working at Apollo Agriculture. Harun is passionate about Android development, never tired of learning, building the tech community, and helping other developers upscale their skills. He is a co-organizer at Droidcon Kenya and a former Kotlin Kenya and Android254 co-organizer. Through these communities, he has been able to impact thousands of developers. He is also an Android author at Kodeco where he has written 8 articles, published a book; Saving Data on Android, Second Edition, and is also a video course instructor. He has given numerous sessions on Android and Kotlin across different communities worldwide.
Read more about Harun Wangereka

Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
Mastering Kotlin for Android 14
Published in: Apr 2024Publisher: PacktISBN-13: 9781837631711
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Harun Wangereka

Harun Wangereka is a Google Developer Expert for Android and an Android engineer with over seven years of experience and currently working at Apollo Agriculture. Harun is passionate about Android development, never tired of learning, building the tech community, and helping other developers upscale their skills. He is a co-organizer at Droidcon Kenya and a former Kotlin Kenya and Android254 co-organizer. Through these communities, he has been able to impact thousands of developers. He is also an Android author at Kodeco where he has written 8 articles, published a book; Saving Data on Android, Second Edition, and is also a video course instructor. He has given numerous sessions on Android and Kotlin across different communities worldwide.
Read more about Harun Wangereka