Basics

Kotlin If Else

Conditional Statements

Kotlin if-else statements double as expressions with type safety.

Understanding Kotlin If-Else Statements

The if-else statement in Kotlin is a control flow structure that allows you to execute different blocks of code based on conditions. Unlike many other languages, Kotlin's if-else can also be used as an expression, meaning it can return a value. This feature adds flexibility and conciseness to your code.

Basic If-Else Statement

In its simplest form, an if-else statement in Kotlin evaluates a condition and executes the corresponding code block. Here is the basic syntax:

Let's consider a simple example where we check if a number is positive or negative:

If-Else as an Expression

In Kotlin, the if-else statement can return values. This means you can use it inline to assign a value to a variable. Here's an example:

In this example, the if-else statement evaluates the condition and assigns the string "Positive" to result if the condition is true, or "Negative or Zero" if false. This approach is both concise and expressive.

Type Safety with If-Else

Kotlin ensures type safety in if-else expressions. The type of the expression is determined by the types of its branches and must be consistent. If the branches return different types, Kotlin will throw a compile-time error.

In the above example, the if-else expression will cause a compile-time error because the branches return different types (Int and String). To fix this, ensure both branches return the same type.

Nested If-Else Statements

You can nest if-else statements to evaluate multiple conditions. This is useful for more complex logic. Here’s an example:

In this example, the nested if-else checks multiple conditions to determine if the number is positive, negative, or zero.

Conclusion

Kotlin's if-else statements are versatile, supporting both traditional control flow logic and expression-based value assignments. Their type safety feature ensures consistent and error-free code, making them a powerful tool in your Kotlin programming toolkit.

Previous
Operators
Next
When