ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

If Else Expression in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='81' AND `tutorial_status`=1 LIMIT 1

If Else Expression in Kotlin

📌 If-Else Expression in Kotlin

In Kotlin, if and else are used for conditional decision-making. Unlike some other languages, Kotlin treats if-else as an expression, meaning it can return a value. This makes it more flexible and concise.


✅ 1. Basic If-Else Statement

You can use if-else like a traditional conditional statement.

📌 Example:

kotlin

fun () { val number = 10 if (number > 0) { println("$number is positive") } 10 is positive

  • if checks the condition number > 0

  • else executes when the condition is false


✅ 2. If-Else Expression

In Kotlin, if-else can be used as an expression to return a value.

📌 Example:

kotlin

fun () { val a = 15 val b = 20 val max = if (a > b) a else b println("The maximum value is $max")}

Output:

csharp

The maximum fun () { val number = -5 val result = if (number > 0) { "Positive" } else if (number < 0) { "Negative" } else { "Zero" } println("The number is $result")}

Output:

cshar

The number fun () { val a = 10 val b = 20 val c = 15 val max = if (a > b) { if (a > c) a else c } else { if (b > c) b else c } println("The maximum value is $max")}

Output:

csharp

The maximum fun main() { val age = 18 if (age >= 18) { println("Eligible to vote") } println("Program completed")}

Output:

css

Eligible to voteProgram completed

  • If the condition is true, the statement executes.

  • If false, it skips the block and moves on.


✅ 6. Conclusion

  • Use if-else as a statement for conditional logic.

  • Use if-else expressions to return values.

  • Combine multiple conditions using else if.

  • Use nested if-else for complex decisions.

  • Kotlin's if is more powerful and concise compared to other languages.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql