0
0
Kotlinprogramming~10 mins

Single-expression functions in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Single-expression functions
Define function with = expression
Function returns expression result
Call function
Output result
A single-expression function in Kotlin uses = to return the result of one expression directly, making code shorter and clearer.
Execution Sample
Kotlin
fun square(x: Int) = x * x

fun main() {
  println(square(4))
}
Defines a single-expression function 'square' that returns x squared, then prints square(4).
Execution Table
StepActionExpression EvaluatedResultOutput
1Call square(4)4 * 416
2Return from square1616
3Print resultprintln(16)16
💡 Function returns after evaluating single expression; main ends after printing.
Variable Tracker
VariableStartAfter callFinal
x-44
square(x)--16
Key Moments - 2 Insights
Why don't we use curly braces {} in single-expression functions?
Single-expression functions use = to return the expression result directly, so curly braces and explicit return are not needed (see execution_table step 1).
What happens if the expression has multiple statements?
Single-expression functions can only have one expression; multiple statements require a block with {} and explicit return.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'square(4)' at step 2?
A16
B4
C8
DError
💡 Hint
Check the 'Result' column at step 2 in the execution_table.
At which step is the output printed to the console?
AStep 1
BStep 3
CStep 2
DNo output printed
💡 Hint
Look at the 'Output' column in the execution_table.
If we replace '=' with '{}' and omit 'return', what happens?
AFunction still works the same
BCompilation error due to missing return
CFunction returns Unit
DFunction returns null
💡 Hint
Single-expression functions require '=' or explicit return in blocks.
Concept Snapshot
Single-expression functions use '=' followed by one expression.
They return the expression result automatically.
No curly braces or return keyword needed.
Example: fun square(x: Int) = x * x
Simplifies code and improves readability.
Full Transcript
This visual trace shows how a Kotlin single-expression function works. The function 'square' is defined with '=' and a single expression 'x * x'. When called with 4, it calculates 4 times 4, returning 16 immediately without curly braces or return keyword. The main function prints this result. The execution table tracks each step: calling the function, returning the result, and printing output. Variables 'x' and 'square(x)' are tracked to show their values. Key moments clarify why '=' is used and that multiple statements need a block. The quiz tests understanding of function return values, output timing, and syntax rules. This helps beginners see how single-expression functions simplify Kotlin code by returning one expression directly.