0
0
Kotlinprogramming~5 mins

If-else expression assignment in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an if-else expression in Kotlin?
In Kotlin, if-else is an expression that returns a value. You can assign the result of an if-else directly to a variable.
Click to reveal answer
beginner
How do you assign a value using if-else expression in Kotlin?
You write: val result = if (condition) value1 else value2. The variable 'result' gets the value based on the condition.
Click to reveal answer
intermediate
Can if-else expression in Kotlin omit the else part when used for assignment?
No. When using if-else as an expression for assignment, you must include the else branch to cover all cases.
Click to reveal answer
beginner
Example: What is the value of 'max' after this code? val a = 5 val b = 10 val max = if (a > b) a else b
The value of 'max' is 10 because 'a > b' is false, so the else branch returns b which is 10.
Click to reveal answer
intermediate
Why is if-else in Kotlin called an expression and not just a statement?
Because it produces a value that can be assigned or used directly, unlike statements which do not return values.
Click to reveal answer
In Kotlin, how do you assign the larger of two numbers a and b to a variable max using if-else expression?
Aval max = if (a > b) a else b
Bval max = if (a > b) { a }
Cval max = if (a > b) a
Dval max = a > b ? a : b
What happens if you omit the else branch in an if-else expression assignment in Kotlin?
AThe variable gets assigned the if branch value or null
BThe else branch is assumed as null
CThe program runs but with a warning
DCompilation error because else is required
Which of these is true about if-else in Kotlin?
AIt must always be followed by a semicolon
BIt can only be used as a statement without returning a value
CIt can be used as an expression that returns a value
DIt cannot be assigned to a variable
What is the output of this Kotlin code? val x = 7 val y = 3 val result = if (x < y) "Less" else "More" print(result)
A"More"
B"Less"
C7
D3
Why might you prefer if-else expression assignment over traditional if-else statements?
AIt is required in all Kotlin code
BIt makes code shorter and clearer by directly assigning values
CIt avoids the need for variables
DIt runs faster than statements
Explain how if-else expressions work in Kotlin and how they differ from traditional if-else statements.
Think about how you can use if-else to get a value directly.
You got /4 concepts.
    Write a Kotlin code snippet that assigns the smaller of two numbers to a variable using if-else expression.
    Use val result = if (condition) value1 else value2
    You got /4 concepts.