logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Kotlin Control Flow

author
Generated by
Akash Agrawal

21/09/2024

Kotlin

Sign in to read full article

Kotlin, an expressive and concise programming language, offers various control flow mechanisms to handle logic in your code. In this post, we'll explore if expressions, when expressions, and loops, which are fundamental for controlling the flow of execution based on certain conditions. Let’s dig into each of these constructs!

1. The if Expression

In Kotlin, if is not just a statement; it can also be used as an expression. This means that you can use it to return values. Below is a basic example to illustrate:

fun main() { val number = 10 val message = if (number > 0) { "The number is positive." } else if (number < 0) { "The number is negative." } else { "The number is zero." } println(message) }

In the code above:

  • We declare a variable number and set it to 10.
  • We use an if expression to check whether the number is positive, negative, or zero.
  • Depending on the condition, the appropriate message is assigned to the message variable.

This behavior shows the versatility of the if expression in Kotlin.

2. The when Expression

The when expression in Kotlin is a powerful and elegant way to handle multiple conditions. It can be seen as a more readable alternative to a series of if statements. Here's how you can use it:

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

In this example:

  • We define a variable day and assign it the integer 2.
  • Using the when expression, we check the value of day against various options.
  • Depending on the value, it returns the corresponding day name.

The when expression also has an interesting feature where you can check ranges or conditions:

fun main() { val score = 85 val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" score >= 60 -> "D" else -> "F" } println("Your grade is $grade") }

In this snippet, instead of using specific values, we are checking ranges of scores to assign grades.

3. Loops in Kotlin

Kotlin offers several types of loops: for, while, and do while. Let’s break down each type.

For Loop

The for loop is used for iterating over ranges, arrays, or collections:

fun main() { for (i in 1..5) { println("Number $i") } }

In the code above:

  • We iterate from 1 to 5 using the .. operator, which creates a range.
  • Each iteration prints the current number.

You can also loop over arrays or collections:

fun main() { val fruits = arrayOf("Apple", "Banana", "Cherry") for (fruit in fruits) { println(fruit) } }

While Loop

The while loop continues executing as long as a specified condition is true:

fun main() { var count = 1 while (count <= 5) { println("Count is $count") count++ } }

Here, the loop continues to execute until count exceeds 5, incrementing with each iteration.

Do While Loop

The do while loop executes at least once before checking the condition:

fun main() { var count = 1 do { println("Counting down: $count") count++ } while (count <= 5) }

In this example, even if the initial condition is false, the loop will execute at least one time.

By understanding and utilizing these control flow constructs like if, when, and loops, you can create powerful and flexible Kotlin applications. In your journey with Kotlin, remember that these basics will form the foundation of more complex logic in your code. Happy coding!

Popular Tags

KotlinControl FlowProgramming

Share now!

Like & Bookmark!

Related Collections

  • Mastering Kotlin: Modern Programming Essentials

    21/09/2024 | Kotlin

Related Articles

  • Getting Started with Jetpack Compose in Kotlin

    03/09/2024 | Kotlin

  • Understanding Coroutines in Kotlin

    03/09/2024 | Kotlin

  • Functional Programming Concepts in Kotlin

    21/09/2024 | Kotlin

  • Testing in Kotlin

    21/09/2024 | Kotlin

  • Introduction to Kotlin and Its Features

    21/09/2024 | Kotlin

  • Kotlin for Backend Development

    03/09/2024 | Kotlin

  • Kotlin Interoperability with Java

    21/09/2024 | Kotlin

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design