Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Conditionals and Logic | Kotlin Basics
Android Development with Kotlin
course content

Course Content

Android Development with Kotlin

Android Development with Kotlin

1. Kotlin Basics
2. Control Flow and Collections
3. Object-Oriented Programming in Kotlin

bookConditionals and Logic

In Kotlin, as in any other programming language, there are logical operators.

This is easy to understand when imagining a situation where we must decide based on a condition. For example:

If more than 100 product units were sold monthly — the product is selling well.

If fewer than 100 units of a product were sold in a month, the product would be selling poorly, and it might be worth considering removing it from sale.

Here's how it will look in the code:

kt

Main

copy
123456789
fun isProductSellingWell(productSalesCount: Int): Boolean { var result: Boolean if (productSalesCount >= 100) { result = true } else { result = false } return result }

Let's break down this function that uses the if-else construct.

First, we declare a new variable called result, then we use the if construct, where we specify a condition inside the parentheses that will execute the action written in the body below.

In our case, if the number of sold products is greater than or equal to 100, the variable result is assigned the value true.

After this, the body of the if part is closed, and the body of the else part is opened. This means that if fewer than 100 units of the product are sold, the variable result is assigned the value false.

After this, the function returns the result.

From this, we can conclude that the if-else construct has the following syntax:

The data type of a condition must always return a Boolean. This means there should be logical operations such as:

  • > - strictly greater than;
  • < - strictly less than;
  • >= - greater than or equal to;
  • <= - less than or equal to;
  • == - the value on the left is equal to the value on the right;
  • != - the value on the left is NOT equal to the value on the right.

These logical comparison operations will return Boolean values. The logic is simple:

"If the operation is true, return true; otherwise, return false."

Here's what it looks like in practice:

kt

Main

copy
12345678910
fun main() { val x: Int = 15 val y: Int = 10 println("Is $x is greater than $y? ${x > y}") println("Is $x equals to $y? ${x == y}") println("Is 30 is less or equal to 30? ${30 <= 30}") }

Let's break down what's happening in the example:

Two variables are created: x and y. Then, within the println() function, we check different logical operations by simply using x > y and similar expressions.

As you can see, the output shows boolean values where we wrote these logical operations. It's all very straightforward.

If-else Chain

A single block can contain more than one condition.

For example, if we need to check if a number equals a certain value and require more than two blocks, you can use an if-else chain.

In simple terms, this chain links multiple if blocks using the else if construct.

Here's how it looks in the code:

kt

Main

copy
1234567891011
fun whatDayIsItToday(dayOfTheWeek: String) { if (dayOfTheWeek == "Friday") { println("It's Friday my dudes!") } else if (dayOfTheWeek == "Saturday") { println("First day of the weekend!") } else if (dayOfTheWeek == "Sunday") { println("Last day of the weekend :(") } else { println("Today is working day!") } }

The function above determines the day of the week, outputting the corresponding message to the console.

As you can see, to use multiple different conditions, we use the else if construct. We specify the condition in parentheses and open the body for that condition, where the code to be executed is written.

Let's see how this method works in practice:

kt

Main

copy
123456789101112131415161718192021
fun main() { val monday: String = "Monday" val sunday: String = "Sunday" val friday: String = "Friday" whatDayIsItToday(monday) whatDayIsItToday(sunday) whatDayIsItToday(friday) } fun whatDayIsItToday(dayOfTheWeek: String) { if (dayOfTheWeek == "Friday") { println("It's Friday my dudes!") } else if (dayOfTheWeek == "Saturday") { println("First day of the weekend!") } else if (dayOfTheWeek == "Sunday") { println("Last day of the weekend :(") } else { println("Today is working day!") } }

But what if there are too many conditions?

`when` Expression

when is a construct similar to switch-case in other languages. It is more flexible and can be used for checking values as well as pattern matching.

This construct also replaces if-else chains effectively, allowing you to handle multiple conditions in a more convenient manner.

Here’s how our function whatDayIsItToday would look if we used the when construct for its implementation:

kt

Main

copy
12345678910111213141516
fun whatDayIsItToday(dayOfTheWeek: String) { when (dayOfTheWeek) { "Friday" -> { println("It's Friday my dudes!") } "Saturday" -> { println("First day of the weekend!") } "Sunday" -> { println("Last day of the weekend :(") } else -> { println("Today is working day!") } } }

In this construct, it's very straightforward to navigate. We simply use the keyword when, specifying the value in parentheses that will determine the actions in the blocks below.

If you read the code linearly, it sounds like this:

"When the value of the variable dayOfWeek is Friday, execute the first block. When the value is Saturday, execute the second block, and so on."

Note the arrow (->) that we use. This arrow is often used for lambda expressions, which we will discuss later. For now, just remember that when using the when construct, you need to use this little arrow.

The general syntax for the when construct looks like this:

The when construct also has other uses; for example, when can be used as an expression that returns a value:

kt

Main

copy
1234567891011121314
fun main() { val dayOfWeek: Int = 3 val dayName = when (dayOfWeek) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid day" } }

This syntax might seem a bit complicated, but it's not as difficult as it appears.

Depending on the value of the variable dayOfWeek, we assign a value to the variable dayName, creating a link between these two variables.

For example, in the code, if it's the third day of the week, which means the name of the day is Wednesday.

You can also read this code as:

"When the day of the week equals 3, assign the value Wednesday to the variable dayName, and so on."

This way, you can create complex associations between variables or other values, which we will need later.

Using Conditions

The when construct can also be used with various conditions, just like if-else.

Let's look at a simple example of how this is done:

kt

Main

copy
12345678
fun main() { val number = 10 when { number % 2 == 0 -> println("Even number") number % 2 != 0 -> println("Odd number") } }

Here, we use the when construct to determine if a number is even. As you can see, no value is specified in the parentheses after when; instead, expressions are provided, followed by an arrow and an action. These are like mini-functions inside the when construct.

The syntax for this format of the when construct looks as follows:

From all this, we can draw one big conclusion: the when construct is a very powerful and convenient tool that can achieve many results.

Combining Multiple Conditions

There are situations where we need to combine several conditions together, using two conditions simultaneously or one of them.

For this, we can use the following tools:

  • && (Logical AND) — returns true if both operands are true.
  • || (Logical OR) — returns true if at least one of the operands is true.
  • ! (Logical NOT) — returns true if the operand is false.

Let's look at a couple of examples where this is used:

kt

Main

copy
1234567891011121314151617
fun main() { val a = 10 val b = 20 val c = 15 if (a < b && b < c) { println("b is between a and c") } if (a > b || b < c) { println("At least one of the conditions is true") } if (!(a > b)) { println("a is not greater than b") } }

As you can see, we use multiple conditions in a single if statement, employing logical AND, OR, and NOT.

With the if-else and when constructs, we can efficiently perform complex operations and handle data effectively in both simple and complex functions.

1. What does the when construct in Kotlin replace from other programming languages?
2. Which logical operator returns `true` if both operands are true in Kotlin?
What does the when construct in Kotlin replace from other programming languages?

What does the when construct in Kotlin replace from other programming languages?

Select the correct answer

Which logical operator returns `true` if both operands are true in Kotlin?

Which logical operator returns true if both operands are true in Kotlin?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 7
some-alt