How to Write CONDITIONALS in Kotlin: if/else, when [2024 Course]

In Kotlin, coding without conditionals is like a recipe without spices – bland and predictable. Using if/else and when adds flavor to your code, allowing it to adapt dynamically. Kotlin’s versatility shines, simplifying expressions and handling complex logic with ease. So spice up your code and let it dance with Kotlin’s conditional salsa! 💃🌶️

Conditional statements are essential in programming, allowing us to define the paths our code will take based on specific conditions. Without them, our code would merely execute actions sequentially, lacking the ability to diverge based on different values. One of the most common conditional statements is the if statement. Let’s explore a simple example by creating a function called printName.

fun printName(name: String) {
    if (name.isEmpty()) {
        println("The name is empty")
    } else {
        println(name)
    }
}

In this example, the if statement checks if the provided name is empty. If true, it prints "The name is empty"; otherwise, it prints the name. To optimize the code, we can use a variable to store the message.

fun printName(name: String) {
    val message = if (name.isEmpty()) "The name is empty" else name
    println(message)
}

This improvement helps avoid redundant code, making it more concise. Kotlin’s expressiveness allows us to further simplify expressions, especially when dealing with straightforward conditions.

🚀 Versatility of Kotlin’s If Statement

The if statement is powerful, but what if we need to handle more complex scenarios? Kotlin introduces the when expression, providing a more flexible alternative. Suppose we want to print different family members based on the provided name.

fun printFamilyMember(name: String) {
    val familyMember = when (name) {
        "Antonio" -> "Father"
        "Tania" -> "Mother"
        "Vera" -> "Daughter"
        "Oscar" -> "Son"
        else -> "Not a family member"
    }
    println(familyMember)
}

Here, the when expression helps us avoid multiple if conditions. It’s crucial to include an else branch to handle cases not covered by the specified conditions, ensuring completeness.

💡 Using when as an Expression

when can also be used as an expression, allowing us to assign its result directly. This enhances code readability and eliminates the need for intermediate variables.

fun getFamilyMember(name: String): String =
    when (name) {
        "Antonio" -> "Father"
        "Tania" -> "Mother"
        "Vera" -> "Daughter"
        "Oscar" -> "Son"
        else -> "Not a family member"
    }

println(getFamilyMember("Vera"))  // Output: Daughter

In this example, getFamilyMember is a concise function that directly returns the family member based on the provided name.

🧐 Advanced Usage of when

Kotlin’s when expression allows us to handle more intricate conditions, making it a versatile tool. We can even use it without explicit conditions, relying on the left side of the expression to determine the path.

val a = 2
val b = "Hello"

when {
    a == 2 -> println("a = 2")
    b == "Hello" -> println("b = Hello")
    else -> println("Default case")
}

In this scenario, the when expression checks conditions directly, similar to an if-else ladder. It’s crucial to note that once a condition is satisfied, subsequent branches are not executed.

🤓 Final Thoughts on Kotlin Conditionals

Understanding how to effectively use if and when expressions in Kotlin provides developers with powerful tools for writing clean and expressive code. Leveraging Kotlin’s concise syntax and flexibility in handling conditions contributes to more efficient and readable programs.

About the Author

DevExpert – Programación Android y Kotlin
40.2K subscribers

About the Channel:

¿Quieres iniciarte con Kotlin hoy? Haz click en el link 👇👇En DevExpert te ayudamos a multiplicar tu valor en el mercado. En nuestro canal encontrarás todo tipo de contenido relacionado con el mundo del desarrollo móvil en Android: desde tutoriales a entrevistas, pasando por noticias, curiosidades, sesiones de preguntas y respuestas en directo y mucho más.En DevExpert nos dedicamos a enseñar a equipos de trabajo y desarrolladores como tú a utilizar las herramientas más top del sector y a dominar Kotlin como lenguaje de programación.Antonio Leiva es formador Android, Google Developer Expert en Android y Kotlin, partner oficial de formación certificado por JetBrains y autor del libro Kotlin for Android Developers.¿Quieres saber más? Entra en https://devexpert.io/Aprende a trabajar con Kotlin en sólo 40 días 👉 https://devexpert.io/training-gratis
Share the Post:
en_GBEN_GB