Consider the following Kotlin code snippet:
val x = 10 val result = if (x > 5) "Greater" else "Smaller or equal" println(result)
What will be printed?
val x = 10 val result = if (x > 5) "Greater" else "Smaller or equal" println(result)
Remember that if-else in Kotlin can be used as an expression that returns a value.
The variable result is assigned the value of the if-else expression. Since x is 10, which is greater than 5, the expression returns "Greater".
Look at this Kotlin code:
val number = 3 val message = if (number % 2 == 0) "Even" else "Odd" println(message)
What will be printed?
val number = 3 val message = if (number % 2 == 0) "Even" else "Odd" println(message)
Check the condition for even numbers using modulo operator.
The number 3 is not divisible by 2, so the else branch "Odd" is assigned to message.
Analyze this Kotlin snippet:
val score = 75
val grade = if (score >= 90) "A"
else if (score >= 80) "B"
else if (score >= 70) "C"
else "F"
println(grade)What is the output?
val score = 75 val grade = if (score >= 90) "A" else if (score >= 80) "B" else if (score >= 70) "C" else "F" println(grade)
Check each condition in order from top to bottom.
The score 75 is less than 80 but greater or equal to 70, so the third condition is true and "C" is assigned.
Consider this Kotlin code snippet:
val x = 5 val y = if x > 3 "Yes" else "No" println(y)
What error will occur?
val x = 5 val y = if x > 3 "Yes" else "No" println(y)
Check the syntax of the if expression in Kotlin.
Kotlin requires parentheses around the condition in an if expression. Missing parentheses cause a syntax error.
Examine this Kotlin code:
val numbers = listOf(1, 2, 3, 4, 5)
val results = numbers.map { if (it % 2 == 0) it * 2 else it * 3 }
println(results.size)How many items does results contain?
val numbers = listOf(1, 2, 3, 4, 5) val results = numbers.map { if (it % 2 == 0) it * 2 else it * 3 } println(results.size)
Remember that map transforms each item but keeps the list size.
The map function applies the if-else expression to each of the 5 items, so the resulting list has 5 items.