0
0
Kotlinprogramming~10 mins

Why expressions over statements matters in Kotlin - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why expressions over statements matters
Start
Write expression
Returns value
Use value directly
More concise & flexible code
End
Expressions produce values that can be used immediately, making code concise and flexible, unlike statements which just perform actions.
Execution Sample
Kotlin
val max = if (a > b) a else b
println(max)
This code uses an if-expression to get the max value between a and b and prints it.
Execution Table
StepExpression EvaluatedConditionResult ValueAction
1a > btruetrueCheck if a is greater than b
2if-expressiontrueaReturns a because condition is true
3val max = ...-max = aAssign max to a
4println(max)-prints value of maxOutput max value
5---End of execution
💡 Execution stops after printing max value.
Variable Tracker
VariableStartAfter Step 3Final
a555
b333
maxuninitialized55
Key Moments - 2 Insights
Why can we assign the result of an if-expression to a variable?
Because in Kotlin, if is an expression that returns a value, not just a statement. See execution_table row 2 where the if-expression returns 'a'.
What is the benefit of expressions returning values?
It lets us write concise code by using the result directly, like assigning max in one line (execution_table row 3), instead of writing multiple statements.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value does the if-expression return at step 2?
Ab
Ba
Ctrue
Dfalse
💡 Hint
Check the 'Result Value' column at step 2 in execution_table.
At which step is the variable max assigned a value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column for assignment in execution_table.
If the condition a > b was false, what would the if-expression return?
Ab
Btrue
Ca
Dfalse
💡 Hint
Recall how if-expressions work: they return the else branch if condition is false.
Concept Snapshot
In Kotlin, expressions return values and can be used directly.
Statements perform actions but don't return values.
Using expressions (like if) makes code concise and flexible.
You can assign expression results to variables.
This reduces code lines and improves readability.
Full Transcript
This visual trace shows why expressions matter in Kotlin. The if-expression evaluates a condition and returns a value, which we assign to max. This lets us write concise code by using the returned value directly. Unlike statements, expressions produce values, enabling flexible and readable code. The execution table tracks each step, showing condition checks, returned values, and assignments. The variable tracker shows how max gets its value after the if-expression. Understanding this helps write better Kotlin code.