Logo
Kotlin Basics
Kotlin BasicsControl Flow

Control Flow

Introduction to loops and conditionals in Kotlin, including their syntax, usage, and best practices for controlling the flow of your program.

Control flow mechanisms are fundamental to any programming language, allowing you to execute different blocks of code based on conditions or repeatedly. Kotlin offers a variety of control flow constructs like if-else statements, when expressions, and loops (for, while). This section will guide you through these constructs.

Conditional Statements

If-Else

The if-else statement is used to execute a block of code based on a condition.

Syntax
if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}
Example
val number = 10
if (number > 5) {
    println("Number is greater than 5")
} else {
    println("Number is less than or equal to 5")
}

When Expression

The when expression is Kotlin's version of the switch statement, but more powerful.

Syntax
when (expression) {
    value1 -> // Code to execute if expression == value1
    value2 -> // Code to execute if expression == value2
    else -> // Code to execute if none of the above conditions are met
}
Example
val grade = 'A'
when (grade) {
    'A' -> println("Excellent")
    'B' -> println("Good")
    else -> println("Needs improvement")
}

Loops

For Loop

The for loop is used to iterate through ranges, arrays, or collections.

Syntax
for (element in collection) {
    // Code to execute for each element
}
Example
for (i in 1..5) {
    println(i)
}

While Loop

The while loop executes a block of code as long as a condition is true.

Syntax
while (condition) {
    // Code to execute while condition is true
}
Example
var count = 1
while (count <= 5) {
    println(count)
    count++
}

Summary and Best Practices

  • Use if-else for simple conditional checks and when for multiple conditions.
  • Prefer for loops when the number of iterations is known in advance.
  • Use while loops for scenarios where the number of iterations is not known beforehand.
  • Always be cautious with loop conditions to avoid infinite loops.

Understanding control flow in Kotlin is crucial for writing dynamic and flexible code. Whether you're developing complex algorithms or simple Android Native applications, these constructs will be your building blocks for implementing logic and repetition.

Book a conversation with us for personalize training today!

Was this helpful?
Logo