The if
statement allows conditional execution of code. Kotlin supports traditional if-else blocks, as well as if as an expression. Letβs explore both.
Letβs start with a simple example:
fun main() { val age = 20 if (age >= 18) { println("You're eligible to vote π³οΈ") } }
age
to 17. What will happen?
Now letβs add a fallback when the condition isnβt true:
fun main() { val temp = 35 if (temp > 30) { println("It's hot outside! βοΈ") } else { println("It's comfortable π") } }
temp = 30
? Will it print hot or comfortable?
Use this when you have more than two conditions to check:
fun main() { val score = 82 if (score >= 90) { println("Grade: A π") } else if (score >= 75) { println("Grade: B π") } else if (score >= 60) { println("Grade: C π") } else { println("Grade: D π¬") } }
Kotlin lets you return values directly from if
. No need for ternary operator!
fun main() { val time = 22 val greeting = if (time < 18) "Good Day" else "Good Evening" println(greeting) }
What does this code print?
fun main() { val isRaining = false val isCloudy = true if (isRaining) { println("Take an umbrella β") } else if (isCloudy) { println("Might rain later, stay alert π₯οΈ") } else { println("Enjoy the sunshine! π") } }
if
to run code conditionally.else
for fallback logic.else if
for multiple checks.if
as an expression (returning a value).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!