Using Conditional Statements Effectively

Tutorial 2 of 5

Using Conditional Statements Effectively in Kotlin

1. Introduction

In this tutorial, we will focus on how to use conditional statements effectively in Kotlin. This includes understanding the use of 'if' and 'when' statements to control the flow of your program based on different conditions.

What will you learn:

  • The concept of conditional statements
  • How to use 'if' statements in Kotlin
  • How to use 'when' statements in Kotlin

Prerequisites:

  • Basic understanding of Kotlin syntax
  • Installed Kotlin compiler or IDE like IntelliJ IDEA

2. Step-by-Step Guide

Concept of Conditional Statements

In programming, conditional statements are used to perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.

'if' Statements in Kotlin

In Kotlin, the structure of an 'if' statement is pretty simple:

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

'when' Statements in Kotlin

'when' is another conditional statement in Kotlin that can be used as an alternative to 'if-else-if' ladders or switches. It is concise and more readable.

when (variable) {
    case1 -> // code to be executed if variable matches case1
    case2 -> // code to be executed if variable matches case2
    else ->  // code to be executed if variable doesn't match any case
}

3. Code Examples

Example 1: 'if' statement

val number = 10
if (number > 0) {
    println("The number is positive")
} else {
    println("The number is not positive")
}

Output:

The number is positive

This code checks if the given number is greater than 0. If it is, it prints "The number is positive"; otherwise, it prints "The number is not positive".

Example 2: 'when' statement

val grade = 'A'
when (grade) {
    'A' -> println("Excellent!")
    'B', 'C' -> println("Well done")
    'D' -> println("You passed")
    else -> println("Invalid grade")
}

Output:

Excellent!

This code checks the value of grade. If it's 'A', it prints "Excellent!", if it's 'B' or 'C' it prints "Well done", if it's 'D' it prints "You passed", and for any other value, it prints "Invalid grade".

4. Summary

In this tutorial, we learned about the use of conditional statements in Kotlin. We covered 'if' and 'when' statements with clear, practical examples. As next steps, you can explore more about Kotlin loops and functions.

5. Practice Exercises

Exercise 1: Write a program in Kotlin to check if a number is even or odd.

Exercise 2: Write a program in Kotlin that uses a 'when' statement to determine the day of the week based on a number (1-7).

Exercise 3: Modify the above program to include an 'else' clause for invalid inputs.

Solutions and explanations will be provided in the next tutorial. Keep practicing!