0
0
Kotlinprogramming~10 mins

If-else expression assignment in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If-else expression assignment
Evaluate condition
Condition true?
NoAssign else value
Yes
Assign if value
Use assigned variable
The program checks a condition, assigns a value based on true or false, then uses that value.
Execution Sample
Kotlin
val age = 20
val category = if (age >= 18) "Adult" else "Minor"
println(category)
Assigns 'Adult' or 'Minor' to category based on age, then prints it.
Execution Table
StepCondition (age >= 18)Branch TakenVariable 'category' AssignedOutput
120 >= 18True"Adult"
2---Prints: Adult
3---Execution ends
💡 Condition evaluated once; variable assigned; output printed; program ends.
Variable Tracker
VariableStartAfter AssignmentFinal
ageundefined2020
categoryundefined"Adult""Adult"
Key Moments - 2 Insights
Why is the if-else used as an expression here, not a statement?
Because in Kotlin, if-else can return a value directly, which is assigned to 'category' as shown in execution_table step 1.
What happens if the condition is false?
The else branch value is assigned to 'category' instead, as the flow shows in the 'Branch Taken' column.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what value is assigned to 'category' when age is 20?
A"Minor"
B20
C"Adult"
Dnull
💡 Hint
Check Step 1 in the execution_table where condition is true and 'category' is assigned.
At which step is the output printed?
AStep 1
BStep 2
CStep 3
DNo output printed
💡 Hint
Look at the 'Output' column in execution_table for when println happens.
If age was 16, how would the 'Branch Taken' column change?
AIt would be 'False'
BIt would be 'True'
CIt would be 'Undefined'
DNo change
💡 Hint
Refer to the condition evaluation in execution_table step 1 and consider age < 18.
Concept Snapshot
Kotlin if-else expression assigns value:
val variable = if (condition) value1 else value2
Condition is checked once.
Variable gets value1 if true, else value2.
Useful for concise assignments.
Full Transcript
This example shows how Kotlin uses if-else as an expression to assign a value to a variable. The program checks if age is 18 or more. If true, it assigns "Adult" to category; otherwise, "Minor". Then it prints the category. The execution table traces the condition check, assignment, and output. Variables age and category change from undefined to their final values. Key points include understanding if-else as an expression returning a value and how the branch taken depends on the condition. The quiz questions help reinforce these steps by asking about assigned values, output timing, and condition outcomes.