Sling Academy
Home/Kotlin/Understanding Conditional Expressions in Kotlin

Understanding Conditional Expressions in Kotlin

Last updated: November 29, 2024

Conditional expressions in Kotlin are a fundamental aspect of the language, enabling developers to branch the flow of execution based on certain conditions. In this article, we'll delve into the most common types of conditional expressions and how to use them effectively.

If Expression

The if expression in Kotlin is used to execute code based on whether a condition is true or false. It can also be used as an expression that returns a value, which is a significant departure from traditional languages like Java or C++.

val a = 10
val b = 20

// If used as a statement
if (a > b) {
    println("a is greater than b")
} else {
    println("b is greater than or equal to a")
}

// If used as an expression
val max = if (a > b) a else b
println("max = ", max)

In the code above, the if expression is used to determine which of the two numbers, a or b, is greater, and the result is assigned to the variable max.

When Expression

The when expression in Kotlin is a powerful tool that serves a similar purpose to the switch statement found in languages like Java. It simplifies complex conditional logic by evaluating an expression against a set of cases.

val x = 3
val result = when (x) {
    1 -> "x is 1"
    2 -> "x is 2"
    3, 4 -> "x is 3 or 4"
    else -> "x is neither 1, 2, 3, nor 4"
}
println(result)

The when expression above checks the value of x and matches it to a corresponding branch, returning the appropriate string.

Elvis Operator

The Elvis operator ?: is a shorthand in Kotlin for providing a default value when working with nullable variables. It is named after the resemblance of its symbol to Elvis Presley's hairstyle.

val str: String? = null
val length = str?.length ?: -1
println("Length of the string is", length)

Here, the Elvis operator is used to return -1 if str is null, otherwise it returns the length of str.

Putting it All Together

Conditional expressions in Kotlin not only enhance the readability but also make the code structured and concise. Understanding how to effectively use these expressions can lead to clearer and more idiomatic Kotlin code.

Next Article: Checking Equality and Inequality of Values in Kotlin

Previous Article: Kotlin - Working with Logical Operators: AND, OR, and NOT

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin