DEV Community

nadirbasalamah
nadirbasalamah

Posted on

Kotlin Tutorial - 2 Control Flow (Condition Selection)

In Kotlin, the condition selection can be done by using if and when statements.

If Statement

This is the basic syntax of if statement. The condition must returns boolean result.

if (condition) {
    // code..
}
Enter fullscreen mode Exit fullscreen mode

In this example, the if statement is used to check if the value is an even number.

fun main() {
    // create number variable
    val number = 12
    // check if number is an even number
    if (number % 2 == 0) {
        // if true, execute this code
        println("even number")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

even number

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the number variable is compared using == operator to check if the result of number % 2 is equals 0. If the result is true, then the code inside if block is executed.

This is the list of comparation operator that can be used in Kotlin.

Operator Description
== Equals to
!= Not equals to
> Greater than
>= Greater than or equals
< Less than
<= Less than or equals

The other operators like AND (&&) and OR (||) is available.

The AND operator is an operator that returns true if the two conditions returns true.

Condition Condition Result
False False False
False True False
True False False
True True True

The OR operator is an operator that returns true if the one or two conditions returns true.

Condition Condition Result
False False False
False True True
True False True
True True True

If else Statement

The if statement can be added with else statement to execute certain code if the condition inside if is not match. This is the basic syntax of using if else statement.

if(condition) {
    // code..
} else {
    // code..
}
Enter fullscreen mode Exit fullscreen mode

This is the example of using if else statement.

fun main() {
    // create name variable
    val name = "firstname"
    // check if name's value is empty
    if (name.isEmpty()) {
        println("name is empty!")
    } else {
        println("Hello, $name !")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Hello, firstname !

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the if else statement is used to check if the value from name variable is empty by using name.isEmpty(). Because the value of name variable is not empty, the code inside else block is executed.

Another way to create condition selection is using if else if statement. This statement is suitable to select many conditions.

In this example, the variable called score is checked to get the score's predicate.

fun main() {
    // create score variable
    val score = 78
    // check the score's value to get the score's predicate
    if (score >= 90) {
        println("Excellent")
    } else if (score < 90 && score >= 75) {
        println("Very Good")
    } else if(score < 75 && score >= 55) {
        println("Good")
    } else if(score < 55) {
        println("Bad")
    } else {
        println("Very Bad")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Very Good

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the if else if is used to check the value from score variable to get the score's predicate.

In Kotlin, to specify a range condition can be done by using in keyword followed with range specification.

// range from 1 until 10
score in 1..10
Enter fullscreen mode Exit fullscreen mode

In this example, the range condition is used to get the score's predicate from score variable.

fun main() {
    // create score variable
    val score = 78
    // check the score's value to get the score's predicate
    if (score >= 90) {
        println("Excellent")
    } else if (score in 75..89) {
        println("Very Good")
    } else if(score in 55..74) {
        println("Good")
    } else if(score < 55) {
        println("Bad")
    } else {
        println("Very Bad")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Very Good

Enter fullscreen mode Exit fullscreen mode

The nested condition selection is also available. This is the example of using nested condition selection using if.

fun main() {
    val email = "test@test.com"
    val password = "secret"

    if(email.equals("test@test.com")) {
        println("Email is valid")
        if (password.equals("secret")) {
            println("Password is valid")
        }
    } else {
        println("Email or password is invalid!")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Email is valid
Password is valid

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the outer if is executed first then the inner if is executed.

When Statement

Condition selection with when statement is similiar with switch case condition selection. This is the basic syntax of using when statement.

when(variable_to_be_checked) {
    condition -> // single code..
    condition -> {
        // multiple line of codes with curly braces.
    }
    ..
    else -> // code for "default" condition..
}
Enter fullscreen mode Exit fullscreen mode

In this example, the when statement is used to get the job's description from job variable.

fun main() {
    val job = "Front End Developer"

    when(job) {
        "Front End Developer" -> println("Develop Front End App")
        "Back End Developer" -> {
            println("Develop Back End App")
            println("Having Fun with server")
        }
        "Mobile Developer" -> println("Develop Mobile App")
        else -> println("Just Do It")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Develop Front End App

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the when statement is using job variable to check the variable's value that suitable with the specified condition. Because the value of job variable is equals to Front End Developer, the code is executed.

Notes

  • The if statement is suitable for complex condition, for example a range condition.
  • The when statement is suitable for simple condition with multiple cases.

Sources

  • Learn more about condition selection in this link.

I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.

Oldest comments (0)